I am trying to automatically open a Word Document in Python. I am very new to programming and I heard this site helped people who had trouble with it.
I have looked at various questions and have found this:
DummyFile = path_to_docx
with open(DummyFile) as f:
source_stream = io(f.read())
document = doc(source_stream)
source_stream.close()
But when I run it, I get:
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 74: character maps to <undefined>
It seems that this code is not what I want. I believe it is trying to read my document and put it into a variable. Not what I want. I want the command, that when executed, will open the word document in Microsoft Word
Expected Result:
Word Document opens in Microsoft Word, as can be seen here:
Practical Data Science using PythonTo read a word document we take help of the module named docx. We first install docx as shown below. Then write a program to use the different functions in docx module to read the entire file by paragraphs. We use the below command to get the docx module into our environment.
Microsoft Word Press the keyboard shortcut Ctrl + O , or click the File tab in the Ribbon and click Open. Go to the location of the document you want to duplicate. Right-click the file, and click Open as copy. A new file opens and is named Copy of Document, Document 2, or similar.
Reading Word Documents docx file in Python, call docx. Document() , and pass the filename demo. docx. This will return a Document object, which has a paragraphs attribute that is a list of Paragraph objects.
You can use python-docx2txt library to read text from Microsoft Word documents. It is an improvement over python-docx library as it can, in addition, extract text from links, headers and footers. It can even extract images. You can install it by running: pip install docx2txt .
On Windows, you can use os.startfile
:
import os
os.startfile('C:\\Path\\To\\file.docx')
For other operating systems, see this answer: https://stackoverflow.com/a/435669/101087
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With