DEAR PEOPLE FROM THE FUTURE: Here's what we've figured out so far...

Welcome! This is a Q&A website for computer programmers and users alike, focused on helping fellow programmers and users. Read more

What are you stuck on? Ask a question and hopefully somebody will be able to help you out!
+4 votes

I have a need to build a list of all the files (only files, no directories) in a folder and its subfolders. I'm using pathlib like this

import pathlib
for filename in pathlib.Path(".").rglob("*"):
    print(filename)

code above works great with one exception: it returns the path of subfolders too, but I only want the files. Here's an example:

My tree

./file_x
./file_y
./subfolder1/file_x
./subfolder1/file_y

Code returns

./file_x
./file_y
./subfolder1
./subfolder1/file_x
./subfolder1/file_y

What I need

./file_x
./file_y
./subfolder1/file_x
./subfolder1/file_y
by
edited by

1 Answer

+2 votes
 
Best answer
for filename in (i for i in pathlib.Path(".").rglob("*") if i.is_file()):
    print(filename)
by
selected by
+1

This is the correct answer. I'd like to make the answer less cryptic by pointing out that the return type of rglob() is a "generator" of <class 'pathlib.PosixPath'>, and is_file() is called on this type. The expression (...) in the for loop is another generator expression.

Contributions licensed under CC0
...