python – Printing File Names

python – Printing File Names

Use the glob module.

The glob module finds all the pathnames matching a specified pattern

import glob, os
parent_dir = path/to/dir
for pdf_file in glob.glob(os.path.join(parent_dir, *.pdf)):
    print (pdf_file)

This will work on Windows and *nix platforms.


Just make sure that your path is fully escaped on windows, could be useful to use a raw string.

In your case, that would be:

import glob, os
parent_dir = rC:Test
for pdf_file in glob.glob(os.path.join(parent_dir, *.pdf)):
    print (pdf_file)

For only a list of filenames (not full paths, as per your comment) you can do this one-liner:

results = [os.path.basename(f) for f in glob.glob(os.path.join(parent_dir, *.pdf)]

Right now, you search each character string inside of testdirs variable.

so its searching the folder for values C, :, , T etc. Youll want to also escape your escape character like C:……

You probably was to use os.listdir(testdir) instead.

python – Printing File Names

Try running your Python script from C:. From the Command Prompt, you might wanna do this:

> cd C:    
> python C:UserspcuserEricDocsTest.py

As pointed out by Tony Babarino, use rC:Test instead of C:Test in your code.

Leave a Reply

Your email address will not be published.