Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Docx files via python

Does anyone know a python library to read docx files?

I have a word document that I am trying to read data from.

like image 757
helloworld Avatar asked Aug 27 '26 01:08

helloworld


2 Answers

There are a couple of packages that let you do this. Check

  1. python-docx.

  2. docx2txt (note that it does not seem to work with .doc). As per this, it seems to get more info than python-docx. From original documentation:

import docx2txt

# extract text
text = docx2txt.process("file.docx")

# extract text and write images in /tmp/img_dir
text = docx2txt.process("file.docx", "/tmp/img_dir") 
  1. textract (which works via docx2txt).

  2. Since .docx files are simply .zip files with a changed extension, this shows how to access the contents. This is a significant difference with .doc files, and the reason why some (or all) of the above do not work with .docs. In this case, you would likely have to convert doc -> docx first. antiword is an option.

like image 127
sancho.s ReinstateMonicaCellio Avatar answered Aug 29 '26 15:08

sancho.s ReinstateMonicaCellio


python-docx can read as well as write.

doc = docx.Document('myfile.docx')
allText = []
for docpara in doc.paragraphs:
    allText.append(docpara.text)

Now all paragraphs will be in the list allText.

Thanks to Automate the Boring Stuff with Python by Al Sweigart for the pointer.

like image 39
Todd Vanyo Avatar answered Aug 29 '26 14:08

Todd Vanyo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!