我有一组文本文档(基本上它们是作为文本文件保存的电子邮件。)我必须阅读这些并写入CSV或Pandas数据框。每行应该有一个电子邮件/文本文件。
我是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()
答案 0 :(得分:0)
你可以从这里开始工作:
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
P.S。
这项工作与python 3.6,良好的工作
答案 1 :(得分:0)
这里提供的答案有效: 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()])