如何用Python将多个文本文件转换为一个CSV文件?

170 阅读1分钟

你可以在Python中把多个文本文件合并成一个CSV文件,方法是使用glob.glob('./*.txt') 表达式来过滤掉给定文件夹中所有文本文件的路径名称。然后遍历所有这些路径名,用 [open()](https://blog.finxter.com/python-open-function/)函数来读取文件内容,并将其写入CSV中。

例子:合并这些文件

这里是简单的例子。

import glob

with open('my_file.csv', 'a') as csv_file:
    for path in glob.glob('./*.txt'):
        with open(path) as txt_file:
            txt = txt_file.read() + '\n'
            csv_file.write(txt)
        

结果输出的CSV文件显示,所有的文本文件都被合并了。

你可以通过使用函数替换分隔符(例如,从单个空位到逗号)。 [txt.replace(' ', ',')](https://blog.finxter.com/python-string-replace-2/)函数,然后再将其写入CSV中。

import glob

with open('my_file.csv', 'a') as csv_file:
    for path in glob.glob('./*.txt'):
        with open(path) as txt_file:
            txt = txt_file.read() + '\n'
            txt = txt.replace(' ', ',')
            csv_file.write(txt)
        


产生的CSV文件用逗号字符整齐地分开。

如果你需要一些更高级的方法来将文本文件转换为CSV,你可能想看看Pandas的 [read_csv()](https://blog.finxter.com/how-to-read-specific-columns-from-csv-file-in-python/)函数,将CSV读入一个DataFrame。

只要你把它作为一个DataFrame,你就可以进行高级处理,如[合并]、[列选择]、[切片]等。