python - 从同一文件夹中的多个文件创建一个 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)
我不知道最后如何创建一个唯一的文件。你能看看上面的代码并告诉我如何获得所需的输出以及我是否遗漏了什么?
解决方案
你不需要在这里做任何复杂的事情。您知道标题行,并且您知道您希望决赛是除标题之外的所有内容。只需打开文件,跳过第一行,然后写入。这比内存中一堆数据帧的内存消耗要高效得多。
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)
推荐阅读
- eclipse - “显示”视图在“Spring Tool Suite 版本:3.9.6.RELEASE”中的任何透视图中都不可见
- javascript - 如何使用 Angular 6 设置永久迭代
- objective-c - Xcode 10 Objective-C #import 文件名完成不起作用
- javascript - 将外部 JavaScript(来自 cdn)捆绑到 React 组件中
- scala - Spark sql group by和sum改变列名?
- java - 我如何用java语言对数据进行分组和转换
- css - 带有 iframe 的引导模式仅在 iPhone 上不允许垂直滚动
- java - 在我的代码中出现错误如何解决?
- node.js - 快速选择机器人框架
- java - 为 SPA 应用程序集成 openid 连接的最佳方式