2017-08-03 76 views
1

我有一組文本文檔(基本上它們是保存爲文本文件的電子郵件)。我必須讀取這些文檔並以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() 
+0

能否請你告訴你已經嘗試了什麼?如果您表明自己已經努力解決您的問題,用戶將更願意爲您提供幫助。 –

+0

@ChristianDean - 謝謝。我更新了我使用的代碼 –

回答

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 

附:

與Python 3.6,良好的工作這項工作

+0

感謝您的回答。我有一個基本問題。我可以知道我們將在哪裏提及目錄名稱。與我在代碼中提到的類似(我已經編輯了我的問題)。謝謝。 –

+0

例如變量'output'可以是'example.csv'或'Desktop/example.csv' –

+0

我的意思是包含輸入文本文件的目錄。 –

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()]) 
相關問題