【发布时间】:2021-09-22 21:30:21
【问题描述】:
我在一个文件夹中有几个文本文件,我想将它们转换为 csv。在每一行中,我想在一列中包含我的文件名,在另一列中包含内容,例如:
file1.txt,该文件中包含的所有文本
file2.txt,这里有更多文字
...
我正在使用以下代码:
from glob import glob
import pandas as pd
files=os.listdir("where the text files are saved")
content=[]
for file in files:
with open(file, 'r', newline='') as source_file:
for line in csv.reader(source_file):
content.append(line[0])
with open('output.csv', 'w') as target_file:
for line in content:
target_file.write(out_filename + "," + line + '\n')
但是,使用此代码,我只能在 csv 中获取文本文件的内容。谁能解释我如何在列中添加文件名?
【问题讨论】: