[英]Merging multiple .txt files in .csv file line by line
我有一個包含很多.txt文件的文件夾。 我想將所有.txt文件逐行/逐行合並到單個.csv文件中。
我嘗試了以下python代碼,它們工作正常,但我必須更改.txt文件名才能將內容添加到.csv行中。
import re
import csv
from bs4 import BeautifulSoup
raw_html = open('/home/erdal/Dropbox/Marburg/LA/LT_CORPUS/fsdl.txt')
cleantext = BeautifulSoup(raw_html, "lxml").text
#print(cleantext)
print (re.sub('\s+',' ', cleantext))
#appending to csv as row
row = [re.sub('\s+',' ', cleantext)]
with open('LT_Corpus.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(row)
csvFile.close()
我希望看到更好,更快的解決方案,以在不更改文件名的情況下實現流程自動化。 歡迎任何建議。
以下內容將使您更接近所需的內容。
import os
將使您可以訪問os.listdir()
函數,該函數列出目錄中的所有文件。 如果數據文件與腳本不在同一文件夾中,則可能需要提供數據文件夾的路徑。
看起來應該像這樣: os.listdir('/home/erdal/Dropbox/Marburg/LA/LT_CORPUS/')
使用該目錄中的所有文件名,然后可以通過使用for
循環解析每個文件名來分別打開每個文件名。
import re
import csv
from bs4 import BeautifulSoup
import os
filenames = os.listdir('/home/erdal/Dropbox/Marburg/LA/LT_CORPUS/')
for file in filenames:
raw_html = open('/home/erdal/Dropbox/Marburg/LA/LT_CORPUS/' + file)
cleantext = BeautifulSoup(raw_html, "lxml").text
output = re.sub('\s+',' ', cleantext) # saved the result using a variable
print(output) # the variable can be reused
row = [output] # as needed, in different contexts
with open('LT_Corpus.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(row)
其他一些細微差別 :我在csvfile.close()
刪除了csvfile.close()
函數調用。 with
上下文管理器with
使用with
,當離開上下文管理器代碼塊的范圍(即with
語句下面的縮進部分)時,上下文管理器會自動為您關閉文件。 話雖如此,簡單地打開csv
文件,使其保持打開狀態,然后逐個打開txt
文件,然后將其內容寫入打開的csv
,直到最后關閉csv
有益的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.