You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
"""
|
|
|
|
|
模块功能:该模块作为工具箱,包含了数据读取和数据保存的功能。
|
|
|
|
|
|
|
|
|
|
函数:
|
|
|
|
|
read_csv(file_path): 从 CSV 文件中读取数据并返回pd.DataFrame对象。
|
|
|
|
|
save_csv(df, file_path): 将pd.DataFrame对象保存为 CSV 文件。
|
|
|
|
|
"""
|
|
|
|
|
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def read_csv(file_path: str) -> pd.DataFrame:
|
|
|
|
|
"""
|
|
|
|
|
从 CSV 文件中加载 DataFrame 对象。
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
file_path (str): CSV 文件的路径。
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
DataFrame: 从 CSV 文件中加载的 DataFrame 对象。
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
df = pd.read_csv(file_path, index_col="date", parse_dates=["date"])
|
|
|
|
|
print(f"成功读取文件: {file_path}")
|
|
|
|
|
except FileNotFoundError:
|
|
|
|
|
print(f"找不到文件: {file_path}")
|
|
|
|
|
df = pd.DataFrame()
|
|
|
|
|
except Exception as e:
|
|
|
|
|
print(f"读取文件时发生错误: {e}")
|
|
|
|
|
df = pd.DataFrame()
|
|
|
|
|
return df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def save_csv(df: pd.DataFrame, file_path: str) -> None:
|
|
|
|
|
"""
|
|
|
|
|
将 DataFrame 对象保存为 CSV 文件。
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
df (DataFrame): 要保存的 DataFrame 对象。
|
|
|
|
|
file_path (str): CSV 文件的路径。
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
df.to_csv(file_path, index_label='date')
|
|
|
|
|
print(f"成功保存文件: {file_path}")
|
|
|
|
|
except Exception as e:
|
|
|
|
|
print(f"保存文件时发生错误: {e}")
|