[英]Combining csv with Python in new line
我試圖連接多個 csv 但 output 文件在一行中包含所有數據。 如何在給出 output 時添加換行符。 這是我的示例代碼
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 。 但對我沒有用。 文件有變化嗎?
您是否需要 pandas 來連接一堆 csv? 如果您使用的是 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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.