如何在Python中将多个.txt文件转换为.csv文件

如何在Python中将多个.txt文件转换为.csv文件,python,pandas,csv,file-io,concatenation,Python,Pandas,Csv,File Io,Concatenation,我正在尝试使用Python将多个文本文件转换为单个.csv文件。我目前的代码是: import pandas import glob #Collects the files names of all .txt files in a given directory. file_names = glob.glob("./*.txt") #[Middle Step] Merges the text files into a single file titled 'output_

我正在尝试使用Python将多个文本文件转换为单个.csv文件。我目前的代码是:

import pandas
import glob

#Collects the files names of all .txt files in a given directory.
file_names = glob.glob("./*.txt")

#[Middle Step] Merges the text files into a single file titled 'output_file'.
with open('output_file.txt', 'w') as out_file:
    for i in file_names:
        with open(i) as in_file:
            for j in in_file:
                out_file.write(j)

#Reading the merged file and creating dataframe.
data = pandas.read_csv("output_file.txt", delimiter = '/')
  
#Store dataframe into csv file.
data.to_csv("convert_sample.csv", index = None)
如您所见,我正在读取所有文件,并将它们合并为一个.txt文件。然后我将其转换为一个.csv文件。有没有办法不经过中间步骤就完成这一点?是否有必要将所有的.txt文件连接成一个.txt文件以将其转换为.csv,或者是否有方法将多个.txt文件直接转换为一个.csv文件


非常感谢。

当然可以。您真的不需要在这里涉及熊猫,只需使用标准库
csv
模块即可。如果您提前知道列名,最简单的方法是使用
csv.DictWriter
csv.DictReader
对象:

import csv
import glob

column_names = ['a','b','c'] # or whatever


with open("convert_sample.csv", 'w', newline='') as target:
    writer = csv.DictWriter(target, fieldnames=column_names)
    writer.writeheader() # if you want a header
    for path in glob.glob("./*.txt"):
        with open(path, newline='') as source:
            reader = csv.DictReader(source, delimiter='/', fieldnames=column_names)
            writer.writerows(reader)
        

您可能希望在“中间步骤”上添加注释。我认为您的代码没有问题,因为它可以完成您所说的所有需要的操作。您提前知道列名吗?是的,列名将提前知道,并且对于所有文本文件都是相同的。一次将有3到5个文本文件需要转换。是!感谢您注意到stdlib
csv
模块足以满足此要求。令人不安的是,人们经常愿意添加
pandas
,将其作为仅用于基本csv处理的依赖项。@MichaelRuth是的,这真让我恼火。