简体   繁体   English

用python合并CSV文件

[英]Merge CSV files with python

I have a folder of around 200 CSV files. 我有一个约200个CSV文件的文件夹。 Each only have values in the first row. 每个仅在第一行中具有值。 How do I combine the files so that is each CSV file becomes a row in the new dataset. 如何合并文件,以便每个CSV文件在新数据集中都成为一行。

For example: 例如:

1.csv contains:
[1, 2, 3, 4, 5, 6]
2.csv contains:
[2, 3, 4, 5, 5, 7]

I want to combine the CSV's so that the final CSV looks like: 我想合并CSV,以便最终的CSV看起来像:

final.csv contains:
[1, 2, 3, 4, 5, 6]
[2, 3, 4, 5, 5, 6]

*Each matrix is a row of the .csv, and each , means a new cell. *每个矩阵都是.csv的一行,每个表示一个新单元格。

Thank You! 谢谢!

If you have bash, you can use 如果您有bash,可以使用

cat *.csv > combined.csv

Or, if you want to do it the python way: 或者,如果您想使用python方式:

import csv

with open('combined.csv', 'wb') as out_file:
    writer = csv.writer(out_file)
    for fname in os.listdir('.'):
        with open(fname, 'rb') as in_file:
            for row in csv.reader(in_file):
                writer.writerow(row)

Here you'll need to navigate to the directory containing your 200 odd csv files. 在这里,您需要导航到包含200个csv文件的目录。

  • windows cmd - type copy *.csv combined.csv Windows cmd-输入复制* .csv Combined.csv

  • linux bash - cat file1.csv file2.csv > combined.csv linux bash -cat file1.csv file2.csv> Combined.csv

  • python - something like python-类似

     fout=open("out.csv","a") for num in range(1,201): for line in open("sh"+str(num)+".csv"): fout.write(line) fout.close() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM