使用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)

问题答案:

问题

如您的代码在最后一个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循环中打开一次文件,然后尝试将文件逐段添加。