Python Script To Convert A Docx File To Text File

1 min read

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.


PROGRAMS

Latest Articles

Latest from djangocentral

Capturing Query Parameters of request.get in Django

In Django, the request object contains a variety of information about the current HTTP request, including the query parameters. Query parameters are a way to pass additional information in the URL and are used to filter or sort data. The request object p…
Read more →

2 min read

Understanding related_name in Django Models

In Django, related_name is an attribute that can be used to specify the name of the reverse relation from the related model back to the model that defines the relation. It is used to specify the name of the attribute that will be used to access the relat…
Read more →

2 min read