Python: Convert Text to Word or Word to Text

Text files are a common file type that contain only plain text without any formatting or styles. If you want to apply formatting or add images, charts, tables, and other media elements to text files, one of the recommended solutions is to convert them to Word files.

Conversely, if you want to efficiently extract content or reduce the file size of Word documents, you can convert them to text format. This article will demonstrate how to programmatically convert text files to Word format and convert Word files to text format using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip commands.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows

Convert Text (TXT) to Word in Python

Conversion from TXT to Word is quite simple that requires only a few lines of code. The following are the detailed steps.

  • Create a Document object.
  • Load a text file using Document.LoadFromFile(string fileName) method.
  • Save the text file as a Word file using Document.SaveToFile(string fileName, FileFormat fileFormat) method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a TXT file
document.LoadFromFile("input.txt")

# Save the TXT file as Word
document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
document.Close()

Python: Convert Text to Word or Word to Text

Convert Word to Text (TXT) in Python

The Document.SaveToFile(string fileName, FileFormat.Txt) method provided by Spire.Doc for Python allows you to export a Word file to text format. The following are the detailed steps.

  • Create a Document object.
  • Load a Word file using Document.LoadFromFile(string fileName) method.
  • Save the Word file in txt format using Document.SaveToFile(string fileName, FileFormat.Txt) method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file from disk
document.LoadFromFile("Input.docx")

# Save the Word file in txt format
document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
document.Close()

Python: Convert Text to Word or Word to Text

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.