Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing File Names

I am very new to python and just installed Eric6 I am wanting to search a folder (and all sub dirs) to print the filename of any file that has the extension of .pdf I have this as my syntax, but it errors saying

The debugged program raised the exception unhandled FileNotFoundError
"[WinError 3] The system can not find the path specified 'C:'"
File: C:\Users\pcuser\EricDocs\Test.py, Line: 6

And this is the syntax I want to execute:

import os

results = []
testdir = "C:\Test"
for folder in testdir:
  for f in os.listdir(folder):
    if f.endswith('.pdf'):
        results.append(f)

print (results)
like image 318
Michael Mormon Avatar asked Feb 29 '16 15:02

Michael Mormon


1 Answers

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 = r"C:\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')]
like image 170
Inbar Rose Avatar answered Nov 15 '22 15:11

Inbar Rose