How to convert .docx to .txt in Python

Viewed 12707

I would like to convert a large batch of MS Word files into the plain text format. I have no idea how to do it in Python. I found the following code online. My path is local and all file names are like cx-xxx (i.e. c1-000, c1-001, c2-000, c2-001 etc.):

from docx import [name of file]
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,"c", encoding="utf-8") as textFile:
            for para in document.paragraphs: 
                textFile.write(unicode(para.text))

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

Convert docx to txt with pypandoc:

import pypandoc

# Example file:
docxFilename = 'somefile.docx'
output = pypandoc.convert_file(docxFilename, 'plain', outputfile="somefile.txt")
assert output == ""

See the official documentation here:

https://pypi.org/project/pypandoc/

GroupDocs.Conversion Cloud SDK for Python supports 50+ file formats conversion. Its free plan provides 150 free API calls monthly.

# Import module
import groupdocs_conversion_cloud
from shutil import copyfile

# Get your client_id and client_key at https://dashboard.groupdocs.cloud (free registration is required).
client_id = "xxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
client_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# Create instance of the API
convert_api = groupdocs_conversion_cloud.ConvertApi.from_keys(client_id, client_key)

try:

        #Convert DOCX to txt
        # Prepare request
        request = groupdocs_conversion_cloud.ConvertDocumentDirectRequest("txt", "C:/Temp/sample.docx")

        # Convert
        result = convert_api.convert_document_direct(request)       
        copyfile(result, 'C:/Temp/sample.txt')
        
except groupdocs_conversion_cloud.ApiException as e:
        print("Exception when calling get_supported_conversion_types: {0}".format(e.message))
Related