-1

I'm pretty new to Python and I'm using the Python-docx module to manipulate some docx files. I'm importing the docx files using this code:

doc = docx.Document('filename.docx')

The thing is that I need to work with many docx files and in order to avoid write the same line code for each file, I was wondering, if I create a folder in my working directory, is there a way to import all the docx files in a more efficient way?

TomasDanke
  • 11
  • 4
  • What have you tried so far? Please remember this site is used to help get past road blocks, not write your code for you. Please let us know where you’re stuck and what you’ve tried. – S3DEV Apr 02 '20 at 16:21
  • I agree with commenter above. Small hint use os.scandir, you can find working code in the docs – Anton Pomieshchenko Apr 02 '20 at 16:27
  • I've been using doc = docx.Document('filename.docx') to import one by one. @AntonPomieshchenko thanks – TomasDanke Apr 02 '20 at 16:34

1 Answers1

1

Something like:

from glob import glob

def edit_document(path):
    document = docx.Document(path)
    # --- do things on document ---

for path in glob.glob("./*.docx"):
    edit_document(path)

You'll need to adjust the glob expression to suit.

There are plenty of other ways to do that part, like os.walk() if you want to recursively descend directories, but this is maybe a good place to start.

scanny
  • 26,423
  • 5
  • 54
  • 80