将多个CSV文件中的一行附加到另一个CSV文件

2024-10-02 20:30:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python 3和pandas。我有一个包含多个CSV文件的文件夹,每个文件都包含一个国家所有地区在给定日期的统计数据。我已经为我为每个区域创建的CSV文件创建了另一个文件夹,其中一个为第一个文件夹中CSV文件中列出的每个区域命名。我想将第一组文件中的每个文件的相应行附加到第二个文件夹中各自的区域文件中

This shows a portion of a CSV file from first folder

This shows the CSV files I created in the second folder

下面是我在第二个文件夹中创建了一组新的区域命名文件后运行的代码。我没有得到任何错误,但我也没有得到我想要的结果,这是第二个文件夹中每个区域的CSV文件,包含第一个文件夹中每个文件的每日统计数据

 for csvname in os.listdir("NewTables"):
    if csvname.endswith(".csv"):
        df1 = pd.read_csv("NewTables/"+ csvname)
        name1 = os.path.splitext(filename)[0]
        for file in os.listdir():
            if file.endswith(".csv"):
                df2 = pd.read_csv(file)
                D = df2[df2["denominazione_regione"] == name1 ]
                df1.append(D, ignore_index = True)
                df1.to_csv("NewTables/"+ csvname)

以下是第一个文件夹中CSV文件的几行内容:

数据、stato、codice_region、denominazione_region、lat、long、ricoverati_con_sintomi、terapia_intensiva、totale_ospedalizati、isolamento_dominiare、totale_Positive、Variazion_Positive、nuovi_Positive、dimessi_guariti、deceduti、totale_casi、tamponi、note_it、note_en 2020-02-24T18:00:00,ITA,13,Abruzzo,42.35122196,13.39843823,0,0,0,0,0,0,0,0,5,,, 2020-02-24T18:00:00,ITA,17,Basilicata,40.63947052,15.80514834,0,0,0,0,0,0,0,0,0,0,0,, 2020-02-24T18:00:00,ITA,04,P.A.博尔扎诺,46.49933453,11.35662422,0,0,0,0,0,0,0,0,1,


Tags: 文件csvin文件夹区域osfiledf1
1条回答
网友
1楼 · 发布于 2024-10-02 20:30:51

我不会在这里使用熊猫,因为这里几乎没有数据处理,主要是文件处理。所以我会坚持使用csv模块

我会查看第一个目录中的csv文件,然后一次处理一个。对于每一行,我只需将其附加到文件中,并在第二个文件夹中使用相关名称。我假设区域的数量相当小,所以我会保持第二个文件夹中的文件处于打开状态,以节省每行的打开/关闭时间

代码可以是:

import glob
import os.path
import csv

outfiles = {}   # cache the open files and the associated writer in 2nd folder
for csvname in glob.glob('*.csv'):     # loop over csv files from 1st folder
    with open(csvname) as fdin:
        rd = csv.DictReader(fdin)      # read the file as csv
        for row in rd:
            path = "NewTables/"+row['denominazione_regione']+'.csv'
            newfile = not os.path.exists(path)   # a new file?
            if row['denominazione_regione'] not in outfiles:
                fdout = open(path, 'a', newline='')  # not in cache: open it
                wr = csv.DictWriter(fdout, rd.fieldnames)
                if newfile:
                    wr.writeheader()   # write header line only for new files
                outfiles[row['denominazione_regione']] = (wr, fdout) # cache
            wr = outfiles[row['denominazione_regione']][0]
            wr.writerow(row)           # write the row in the relevant file
for file in outfiles.values():        # close every outfile
    file[1].close()

相关问题 更多 >