如何将新文件添加到数据帧



我有一个存储CSV文件的文件夹,每隔一段时间就会向该文件夹添加一个新的CSV文件(SAME FORMAT(。

我需要检测新文件并将内容添加到数据帧中。

我当前的代码一次读取所有CSV文件并存储在dataframe中,但当新文件(CSV(添加到文件夹中时,dataframe应该用新CSV的内容进行更新。

import os
import glob
import pandas as pd
os.chdir(r"C:UsersXXXXCSVFILES")
extension = 'csv'
all_filenames = [i for i in glob.glob('*.{}'.format(extension))]
#combine all files in the list
df = pd.concat([pd.read_csv(f) for f in all_filenames ])

假设您有一个进入下载新csv的文件夹的路径:

path_csv = r"C:........csv_folder"

我假设您的数据帧(您想要附加到的数据帧(已经创建,并且您将其加载到脚本中(您可能以前更新过它,保存到另一个文件夹中的某个csv中(。假设你这样做:

path_saved_df = r"C:/..../saved_csv"   #The path to which you've saved the previously read csv:s
filename = "my_old_files.csv"
df_old = pd.read_csv(path + '/' +filename, sep="<your separator>")  #e.g. sep =";"

然后,要只读取path中文件夹中最近添加的csv,只需执行以下操作:

list_of_csv = glob.glob(path_csv + "\\*.csv")
latest_csv = max(list_of_csv , key=os.path.getctime)   #max ensures you only read the latest file
with open(latest_csv) as csv_file:
    csv_reader = csv.reader(csv_file , delimiter=';')
    
new_file = pd.read_csv(latest_csv, sep="<your separator>", encoding ="iso-8859-1") #change encoding if you need to

你的新数据帧就是

New_df = pd.concat([df_old,new_file])

最新更新