使用Python将DOCX文件转换为文本文件

时间:2018-10-09 10:50:35

标签: python file-conversion python-docx

我编写了以下代码,将docx文件转换为文本文件。我在文本文件中打印的输出是整个文件的最后一个段落/部分,而不是完整的内容。代码如下:

from docx import Document
import io
import shutil

def convertDocxToText(path):
    for d in os.listdir(path):
        fileExtension=d.split(".")[-1]
        if fileExtension =="docx":
            docxFilename = path + d
            print(docxFilename)
            document = Document(docxFilename)


# for printing the complete document
            print('\nThe whole content of the document:->>>\n')
            for para in document.paragraphs:
                textFilename = path + d.split(".")[0] + ".txt"
                with io.open(textFilename,"w", encoding="utf-8") as textFile:
                    #textFile.write(unicode(para.text))
                    x=unicode(para.text)
                    print(x) //the complete content gets printed by this line
                    textFile.write((x)) #after writing the content to text file only last paragraph is copied.
                #textFile.write(para.text)

path= "/home/python/resumes/"
convertDocxToText(path)

2 个答案:

答案 0 :(得分:1)

问题

如您的代码在上一个for循环中所述:

        for para in document.paragraphs:
            textFilename = path + d.split(".")[0] + ".txt"
            with io.open(textFilename,"w", encoding="utf-8") as textFile:
                x=unicode(para.text)
                textFile.write((x))

对于整个文档中的每个段落,您尝试打开一个名为textFilename的文件,因此假设您在MyFile.docx中有一个名为/home/python/resumes/的文件,因此textFilename的值包含的路径在整个/home/python/resumes/MyFile.txt循环中将始终是for,因此问题在于您以w模式(即Write模式)打开了同一文件,并且覆盖整个文件内容。

解决方案:

您必须从for循环中打开一次文件,然后尝试将文件逐段添加。

答案 1 :(得分:0)

以下是上述问题的解决方案:

from docx import Document
import io
import shutil
import os

def convertDocxToText(path):
    for d in os.listdir(path):
        fileExtension=d.split(".")[-1]
        if fileExtension =="docx":
            docxFilename = path + d
            print(docxFilename)
            document = Document(docxFilename)
            textFilename = path + d.split(".")[0] + ".txt"
            with io.open(textFilename,"w", encoding="utf-8") as textFile:
                for para in document.paragraphs: 
                    textFile.write(unicode(para.text))

path= "/home/python/resumes/"
convertDocxToText(path)