【问题标题】:How to add new file to dataframe如何将新文件添加到数据框
【发布时间】:2021-04-29 01:58:41
【问题描述】:

我有一个存储 CSV 文件的文件夹,每隔一段时间会在文件夹中添加一个新的 CSV 文件(相同格式)。

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

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

import os
import glob
import pandas as pd
os.chdir(r"C:\Users\XXXX\CSVFILES")

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 ])

【问题讨论】:

    标签: pandas csv intervals auto-update


    【解决方案1】:

    假设您的文件夹中有一个路径,其中新的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 =";"
    

    然后,要仅读取最新添加的 csvpath 中的文件夹,您只需执行以下操作:

    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])
    

    【讨论】:

      猜你喜欢
      • 2022-11-28
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 2017-03-11
      相关资源
      最近更新 更多