【发布时间】:2021-08-28 18:12:56
【问题描述】:
我正在尝试使用 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?
非常感谢。
【问题讨论】:
-
您可能想用评论标记您的“中间步骤”。我认为您的代码没有问题,因为它可以满足您所说的一切需求。
-
你提前知道列名吗?
-
是的,列名将提前知道,并且对于所有文本文件都是相同的。一次需要转换 3 到 5 个文本文件。
标签: python pandas csv file-io concatenation