首页 > 解决方案 > 从同一文件夹中的多个文件创建一个 csv 文件

问题描述

我有数千个 csv 文件名称,如下 file_x_x.csv 其中 x 是 1 到 10000 之间的数字,在同一个文件夹中。每个文件包含一个标题和一行数据:

文件_1_1.csv

Name Surname Age Address
Michael O'Donnel 22 George St.

文件_2_2.csv

Name Surname Age Address
Mary Jane 34 Camden St.

等等。

我正在寻找创建一个包含所有这些行的文件:

final_file.csv

Name Surname Age Address
Michael O'Donnel 22 George St.
Mary Jane 34 Camden St.

...

我的做法:

import pandas as pd
import glob

path = # add path
all_files = glob.glob(path + ".csv") # look for all the csv files in that folder. Probably this is not the right code for looking at them

file_list = []

for filename in all_files:
    df = pd.read_csv(filename)
    file_list(df)

我不知道最后如何创建一个唯一的文件。你能看看上面的代码并告诉我如何获得所需的输出以及我是否遗漏了什么?

标签: pythonpandas

解决方案


你不需要在这里做任何复杂的事情。您知道标题行,并且您知道您希望决赛是标题之外的所有内容。只需打开文件,跳过第一行,然后写入。这比内存中一堆数据帧的内存消耗要高效得多。

import glob

with open("final_file.csv", "w") as outfile:
    for count, filename in enumerate(glob.glob(path + ".csv")):
        with open(filename) as infile:
            header = next(infile)
            if count == 0:
                outfile.write(header)
            line = next(infile)
            if not line.startswith("\n"):
                line = line + "\n"
            outfile.write(line)

推荐阅读