[英]Python: Convert all files in directory into one .TXT?
我一直在嘗試將一些 DOCX 文件轉換為 TXT。
它適用於使用以下代碼的單個文件:
import docx
def getText(filename):
doc = docx.Document(filename)
fullText = []
for para in doc.paragraphs:
fullText.append(para.text)
return '\n'.join(fullText)
if __name__ == '__main__':
filename='/content/drive/My Drive/path/file.DOCX'; #file name
fullText=getText(filename)
print (fullText)
file = open("copy.txt", "w")
file.write(fullText)
file.close()
我嘗試了不同的選項(即 glob),但沒有設法讓它對文件夾中的所有文件執行上述操作。
理想情況下,輸出應該是 1 個大文本文件,而不是單獨的文件。 在下一步中,我需要對該文件中的 ID 進行一些格式化和分配。
感謝您的幫助! 公司
使用file = open("copy.txt", "w")
打開文件並用write()
替換其內容。
使用file = open("copy.txt", "a")
您可以使用write()
附加到現有文件。 或者甚至更好:
使用file = open("copy.txt", "a+")
您可以使用write()
附加到現有文件,或者如果尚不存在則創建一個新文件。
要瀏覽文件夾中的所有文件,您可以遍歷它們:
import os
import docx
def getText(filename):
doc = docx.Document(filename)
fullText = []
for para in doc.paragraphs:
fullText.append(para.text)
return '\n'.join(fullText)
if __name__ == '__main__':
foldername='/content/drive/My Drive/path/'; #folder name
all_files = os.listdir(foldername) #get all filenames
docx_files = [ filename for filename in all_files if filename.endswith('.docx') ] #get .docx filenames
file = open("copy.txt", "a+")
for docx_file in docx_files: #loop over .docx files
fullText=getText(filename)
file.write(fullText)
file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.