List only files in a directory?

Using pathlib in Windows as follow:

files = (x for x in Path("your_path") if x.is_file())

Generates error:

TypeError: 'WindowsPath' object is not iterable

You should rather use Path.iterdir()

filePath = Path("your_path")
if filePath.is_dir():
    files = list(x for x in filePath.iterdir() if x.is_file())

Since Python 3.6 you can use glob with a recursive option "**". Note that glob will give you all files and directories, so you can keep only the ones that are files

files = glob.glob(join(in_path, "**/*"), recursive=True)
files = [f for f in files if os.path.isfile(f)]

files = next(os.walk('..'))[2]

This is a simple generator expression:

files = (file for file in os.listdir(path) 
         if os.path.isfile(os.path.join(path, file)))
for file in files: # You could shorten this to one line, but it runs on a bit.
    ...

Or you could make a generator function if it suited you better:

def files(path):
    for file in os.listdir(path):
        if os.path.isfile(os.path.join(path, file)):
            yield file

Then simply:

for file in files(path):
    ...

Tags:

Python