如何使用Python将一组文本文档加载到CSV文件中?
我有一组文本文档(基本上它们是保存为文本文件的电子邮件)。我必须读取这些文档并以CSV或Pandas数据框编写。每行应该带一个电子邮件/文本文件。如何使用Python将一组文本文档加载到CSV文件中?
我是Python新手。我不知道如何解决这个问题。请帮忙。
Filename Content
email1 Content of email 1
email2 Content of email 2
email3 Content of email 3
… …
… …
… …
email n Content of email 7
编辑
我用下面的代码
dirpath = 'path'
output = 'output_file.csv'
with open(output, 'w') as outfile:
csvout = csv.writer(outfile)
csvout.writerow(['FileName', 'Content'])
files = os.listdir(dirpath)
for filename in files:
with open(dirpath + '/' + filename) as afile:
csvout.writerow([filename, afile.read()])
afile.close()
outfile.close()
您可以开始从这里工作:
import csv #is the library
with open('example.csv', 'w') as csvfile: #to create a new csv
fieldnames = ['text']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames) #is the name of column
while length > 0:
writer.writerow({'email': email}) # write a row
length-=1
附:
与Python 3.6,良好的工作这项工作
感谢您的回答。我有一个基本问题。我可以知道我们将在哪里提及目录名称。与我在代码中提到的类似(我已经编辑了我的问题)。谢谢。 –
例如变量'output'可以是'example.csv'或'Desktop/example.csv' –
我的意思是包含输入文本文件的目录。 –
这里提供的答案的工作: Combine a folder of text files into a CSV with each content in a cell
import os
os.chdir('file path')
from pathlib import Path
with open('big.csv', 'w') as out_file:
csv_out = csv.writer(out_file)
csv_out.writerow(['FileName', 'Content'])
for fileName in Path('.').glob('*.txt'):
csv_out.writerow([str(fileName),open(str(fileName.absolute())).read().strip()])
能否请你告诉你已经尝试了什么?如果您表明自己已经努力解决您的问题,用户将更愿意为您提供帮助。 –
@ChristianDean - 谢谢。我更新了我使用的代码 –