简体   繁体   English

如何在Python中将多个文本文件合并为一个csv文件

[英]How to merge multiple text files into one csv file in Python

I am trying to convert 200 text files into csv files.我正在尝试将 200 个文本文件转换为 csv 文件。 I am using below code I am able to run it but it does not produce csv files.我正在使用下面的代码,我可以运行它,但它不会生成 csv 文件。 Could anyone tell any easy and fast way to do?谁能告诉任何简单快捷的方法? Many Thanks非常感谢

dirpath = 'C:\Files\Code\Analysis\Input\qobs_RR1\\'
output = 'C:\Files\Code\Analysis\output\qobs_CSV.csv'
csvout = pd.DataFrame()
files = os.listdir(dirpath)

for filename in files:
    data = pd.read_csv(filename, sep=':', index_col=0, header=None)
    csvout = csvout.append(data)

csvout.to_csv(output)

The problem is that your os.listdir gives you the list of filenames inside dirpath , not the full path to these files.问题是您的os.listdir为您提供了dirpath中的文件名列表,而不是这些文件的完整路径。 You can get the full path by prepending the dirpath to filenames with os.path.join function.您可以通过使用os.path.join函数将dirpath路径添加到文件名中来获取完整路径。

import os
import pandas as pd

dirpath = 'C:\Files\Code\Analysis\Input\qobs_RR1\\'
output = 'C:\Files\Code\Analysis\output\qobs_CSV.csv'
csvout_lst = []
files = [os.path.join(dirpath, fname) for fname in os.listdir(dirpath)]

for filename in sorted(files):
    data = pd.read_csv(filename, sep=':', index_col=0, header=None)
    csvout_lst.append(data)

pd.concat(csvout_lst).to_csv(output)

Edit: this can be done with a one-liner:编辑:这可以用单线完成:

pd.concat(
    pd.read_csv(os.path.join(dirpath, fname), sep=':', index_col=0, header=None)
    for fname in sorted(os.listdir(dirpath))
).to_csv(output)

Edit 2: updated the answer, so the list of files is sorted alphabetically.编辑 2:更新了答案,因此文件列表按字母顺序排序。

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

相关问题 如何将多个 CSV 文件合并到一个文件中,并使用 python 在最终 CSV 文件中创建超级模式 - how to merge multiple CSV files into one file and create super schema in final CSV file using python 如何将多个不同语言的 CSV 文件合并为一个 CSV 文件? - How to merge multiple CSV files with different languages into one CSV file? 如何使用 Python 将 .csv 文件合并到多张工作表中的 one.xls 文件中? - How to merge .csv files into one .xls file in multiple sheets using Python? 如何将多个 csv 文件合并到一个文件中,其中 pandas、python 上有特定列? - How to merge multiple csv files into one file with specific columns on pandas, python? 如何在 python 中打开具有多个数据帧的文件夹并合并到一个 csv 文件中 - how open folder with multiple dataframes in python and merge into one csv file 如何将一些csv文件合并为一个文件 - how to merge some csv files into one file 将多个 csv 文件中的几列合并到一个 csv 文件中 - Merge several columns from multiple csv files to one csv file python中如何将多个json文件合并为一个文件 - How to merge multiple json files into one file in python 将多个csv文件合并为一个 - Merge multiple csv files into one 如果我有一个CSV文件的Python列表,如何将它们全部合并为一个巨型CSV文件? - If I have a Python list of CSV files, how do I merge them all into one giant CSV file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM