如何使用Python将一组文本文档加载到CSV文件中?

如何使用Python将一组文本文档加载到CSV文件中?,python,pandas,Python,Pandas,我有一套文本文档(基本上是作为文本文件保存的电子邮件)。我必须阅读这些文档并在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 编辑 我正

我有一套文本文档(基本上是作为文本文件保存的电子邮件)。我必须阅读这些文档并在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()

您可以从这里开始工作:

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、 美国


这是python 3.6的工作,很好

您可以从这里开始工作:

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、 美国


使用python 3.6的这项工作做得很好

这里提供的答案很有效:


这里提供的答案是有效的:


你能展示一下你的尝试吗?如果你表现出你自己已经努力解决了问题,用户会更愿意帮助你。@ChristianDean-谢谢。我已经用我使用的代码进行了更新。你能展示一下你的尝试吗?如果你表现出你自己已经努力解决了问题,用户会更愿意帮助你。@ChristianDean-谢谢。我已经用我使用的代码更新了谢谢你的回答。我有一个基本问题。我可以知道我们将在哪里提到目录名吗。与我在代码中提到的类似(我现在编辑了我的问题)。谢谢。例如,变量“output”可以是“example.csv”或“Desktop/example.csv”,我指的是包含输入文本文件的目录。您可以在变量中给出它,但这是引用:,我想您可以在这里找到所有信息。如果你需要更多,你可以问,我会尽力帮助你。谢谢你的回答。我有一个基本问题。我可以知道我们将在哪里提到目录名吗。与我在代码中提到的类似(我现在编辑了我的问题)。谢谢。例如,变量“output”可以是“example.csv”或“Desktop/example.csv”,我指的是包含输入文本文件的目录。您可以在变量中给出它,但这是引用:,我想您可以在这里找到所有信息。如果你需要更多,你可以问,我会尽力帮助你。