python - 用python合并CSV文件

标签 python csv

我有一个包含大约 200 个 CSV 文件的文件夹。每个只有第一行的值。我如何合并这些文件,以便每个 CSV 文件成为新数据集中的一行。

例如:

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

我想合并 CSV,以便最终的 CSV 看起来像:

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

*每个矩阵是 .csv 的一行,每个 , 表示一个新单元格。

谢谢!

最佳答案

如果你有bash,你可以使用

cat *.csv > combined.csv

或者,如果你想用 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)

在这里,您需要导航到包含 200 个 csv 文件的目录。

关于python - 用python合并CSV文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44574221/

相关文章:

json - 测试API请求是否正常工作

sql - 使用 CSV 文件中的值更新 Oracle 表

python-3.x - 如何在没有分隔符的情况下从 CSV 创建 Pandas 数据框(在 python 中)

python - 使用 dask 加载大型压缩数据集

bash - 在 csv 文件中输出第一个副本

python - 使用带有 for 循环的字典来比较值

python - Django Sass 压缩器 django_libsass.SassCompiler : command not found

python - 为什么打印语句不能按预期工作?

python - 仅删除在 3D numpy 数组的该行中包含重复项的行

python - 通过套接字从 subprocess.Popen 顺序发送 stdout