怎么使用python3批量轉(zhuǎn)換DOCX文檔為TXT

小億
118
2024-01-18 18:05:05

要使用Python3批量轉(zhuǎn)換DOCX文檔為TXT,可以使用python-docx庫(kù)來(lái)實(shí)現(xiàn)。下面是一個(gè)簡(jiǎn)單的示例代碼:

from docx import Document

def convert_docx_to_txt(docx_file, txt_file):
    doc = Document(docx_file)
    with open(txt_file, 'w', encoding='utf-8') as f:
        for paragraph in doc.paragraphs:
            f.write(paragraph.text + '\n')

# 批量轉(zhuǎn)換
docx_files = ['file1.docx', 'file2.docx', 'file3.docx']
for docx_file in docx_files:
    # 構(gòu)建輸出文件名
    txt_file = docx_file.replace('.docx', '.txt')
    convert_docx_to_txt(docx_file, txt_file)

上述代碼中,convert_docx_to_txt函數(shù)接受一個(gè)DOCX文件路徑和一個(gè)TXT文件路徑作為輸入,將DOCX文檔的內(nèi)容逐行寫入TXT文件中。然后,使用docx_files列表存儲(chǔ)需要轉(zhuǎn)換的DOCX文件名,循環(huán)遍歷列表中的每個(gè)文件,調(diào)用convert_docx_to_txt函數(shù)進(jìn)行轉(zhuǎn)換。

請(qǐng)注意,代碼中使用的是python-docx庫(kù),因此您需要先安裝該庫(kù)。您可以使用以下命令來(lái)進(jìn)行安裝:

pip install python-docx

請(qǐng)確保您已經(jīng)安裝了Python 3和pip,并且將DOCX文件放置在與代碼文件相同的目錄中。

0