0

I am new to programming and am trying to filter out all the files in a directory (= excluding the sub-directories) with Python 3.

My test directory contains 3 PDF files and 2 subfolders, which contain other files. I want to get a Python list containing only the 3 PDF files.

My code (apart from the necessary imports) currently looks like this:

folder_content = listdir(TESTDIRECTORY)
file_list = []
for item in folder_content:
    if path.isfile(item):
        file_list.append(item)
    else:
        pass
print(file_list)

Unfortunatelly this only gives me an empty list: []

Why?

mamr
  • 63
  • 5
  • What is the listdir function you’re calling? Put a print statement in line to to print TESTDIRECTORY to see if it is calling this correctly and a print statement in line 4 to see what files it is identifying and paste output please – thefragileomen Nov 18 '17 at 22:08
  • I solved it. The problem was that os.path.listdir requires [a path-like object](https://docs.python.org/3/library/os.path.html#os.path.isfile) and not just a filename. – mamr Nov 19 '17 at 07:59

0 Answers0