2

I'm using Glob.Glob to search a folder, and the sub-folders there in for all the invoices I have. To simplify that I'm going to add the program to the context menu, and have it take the path as the first part of,

import glob

for filename in glob.glob(path + "/**/*.pdf", recursive=True):

     print(filename)

I'll have it keep the list and send those files to a Printer, in a later version, but for now just writing the name is a good enough test.

So my question is twofold:

  1. Is there anything fundamentally wrong with the way I'm writing this?
  2. Can anyone point me in the direction of how to actually capture folder path and provide it as path-variable?
jhoepken
  • 1,842
  • 3
  • 17
  • 24

2 Answers2

1

You should have a look at this question: Python script on selected file. It shows how to set up a "Sent To" command in the context menu. This command calls a python script an provides the file name sent via sys.argv[1]. I assume that also works for a directory.

Community
  • 1
  • 1
RaJa
  • 1,471
  • 13
  • 17
0

I do not have Python3.5 so that I can set the flag recursive=True, so I prefer to provide you a solution which you can run on any Python version (known up to day).

The solution consists in using calling os.walk() to run explore the directories and the set build-in type.

it is better to use set instead of list as with this later one you'll need more code to check if the directory you want to add is not listed already.

So basically you can keep two sets: one for the names of files you want to print and the other one for the directories and their sub folders.

So you can adapat this solution to your class/method:

import os

path = '.' # Any path you want
exten = '.pdf'
directories_list = set()
files_list = set()
# Loop over direcotries
for dirpath, dirnames, files in os.walk(path):
    for name in files:
        # Check if extension matches
        if name.lower().endswith(exten):
           files_list.add(name)
           directories_list.add(dirpath)

You can then loop over directories_list and files_list to print them out.

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130