python - 在新行中结合 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。但对我没有用。文件有变化吗?
解决方案
你需要 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())
推荐阅读
- episerver - Episerver 未登录无法查看主页
- r - 岭图:按值/等级排序
- python - Postgres 显示错误:输入末尾的语法错误
- git - 是否可以检查 git 提交以包含特定字符?
- python - 从句子中提取特定信息
- google-cloud-platform - 我们如何在 GCP 作曲家环境中使用 GCSToSFTPOperator?
- android - 如何使用 proguard 规则?对于库..即使我添加了库提供的规则仍然应用程序崩溃...如何解决它?
- javascript - 多个 div 的 Readmore 按钮
- javascript - 使用 appendChild 即时添加新表单输入,未触发函数,页面重新加载
- angular - 有没有办法将多个路由解析器堆叠成一个?