我是Python的初学者.我有多个CSV文件(超过10个),并且它们都具有相同数量的列.我想将它们合并到一个CSV文件中,我不会重复标题.
所以基本上我需要只有第一行包含所有标题,然后我需要合并所有CSV文件中的所有行.我该怎么做呢?
任何帮助表示赞赏.
谢谢!
val*_*tin 28
如果您使用的是Linux系统:
head -1 director/one_file.csv > output csv ## writing the header to the final file
tail -n +2 director/*.csv >> output.csv ## writing the content of all csv starting with second line into final file
Run Code Online (Sandbox Code Playgroud)
m.w*_*ski 20
虽然我认为最好的答案是来自@valentin的答案,但您可以在不使用csv模块的情况下完成此操作:
import glob
interesting_files = glob.glob("*.csv")
header_saved = False
with open('output.csv','wb') as fout:
for filename in interesting_files:
with open(filename) as fin:
header = next(fin)
if not header_saved:
fout.write(header)
header_saved = True
for line in fin:
fout.write(line)
Run Code Online (Sandbox Code Playgroud)
如果您不介意开销,可以使用随附常见python发行版的pandas.如果您计划使用speadsheet表做更多,我建议使用pandas而不是尝试编写自己的库.
import pandas as pd
import glob
interesting_files = glob.glob("*.csv")
df_list = []
for filename in sorted(interesting_files):
df_list.append(pd.read_csv(filename))
full_df = pd.concat(df_list)
full_df.to_csv('output.csv')
Run Code Online (Sandbox Code Playgroud)
关于熊猫的更多信息.因为它是为了处理像数据这样的电子表格,所以它知道第一行是标题.在读取CSV时,它将数据表与标题分开,标题保留为dataframepandas中标准数据类型的元数据.如果你dataframes连接其中的几个,它只连接数据集,如果它们的标题是相同的.如果标题不相同则失败并给出错误.如果您的目录被来自其他来源的CSV文件污染,可能是件好事.
另一件事:我刚刚加入sorted()了interesting_files.我假设您的文件按顺序命名,并且应该保留此顺序.我不确定glob,但os函数不一定返回按名称排序的文件.