首页 > 解决方案 > 在新行中结合 csv 和 Python

问题描述

我试图连接多个 csv,但输出文件在一行中包含所有数据。如何在给出输出时添加换行符。这是我的示例代码

from os import chdir
from glob import glob
import pandas as pdlib

# Produce a single CSV after combining all files
def produceOneCSV(list_of_files, file_out):
   # Consolidate all CSV files into one object
   result_obj = pdlib.concat([pdlib.read_csv(file) for file in list_of_files], sort=False)
   # Convert the above object into a csv file and export

   result_obj.to_csv(file_out, index=False, encoding="utf-8")

# Move to the path that holds our CSV files
csv_file_path = 'Path_for_all_the_csv/'
chdir(csv_file_path)

# List all CSV files in the working dir
file_pattern = ".csv"
list_of_files = [file for file in glob('*.csv')]
print(list_of_files)

file_out = "ConsolidateOutput.csv"
produceOneCSV(list_of_files, file_out)

我遵循了文档https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html。但对我没有用。文件有变化吗?

标签: pythonpandascsv

解决方案


你需要 pandas 来连接一堆 csvs 吗?如果您使用的是 linux,则可以使用一个命令来完成。

$ cat *.csv > consolidated.csv

如果你想使用 python

with open("consolidated.json", "w") as f:
    for ff in glob.glob("*.csv"):
        with open(ff) as fff:
            f.write(fff.read())

推荐阅读