Python Script To Convert A Docx File To Text File

In this article, we will learn how to convert a docx file into plain text and then save the content to txt file.

For the conversion, we are going to use a third party package named docx2txt

This tool attempts to generate equivalent plain text files from Microsoft .docx documents, preserving some formatting and document information (which MS text conversion drops) along with appropriate character conversions for a good (ASCII or utf-8) text experience.

It is a platform independent solution consisting of (core) Perl and (wrapper) Unix/Windows shell scripts and a configuration file to control the output text appearance to a fair extent. It can very conveniently be used to build a Web based docx document conversion service.

So first install the package on your machine using pip or any package manager.

pip install docx2txt

Convert A Docx File To Text

import docx2txt

# replace following line with location of your .docx file
MY_TEXT = docx2txt.process("test.docx")

print(MY_TEXT)

Note that test.docx is test file on my desktop having just one line inside for the sake of this tutorial.

Running this script will simply print the content of the file in the terminal.

Output

A line from my awesome docx file

Convert A Docx File To Text File

import docx2txt

# replace following line with location of your .docx file
MY_TEXT = docx2txt.process("test.docx")


with open("Output.txt", "w") as text_file:
    print(MY_TEXT, file=text_file)

This script will convert the docx file’s content into text and then write on a file named Output.txt using Python’s context manager.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Close