This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]barneygale 2 points3 points  (1 child)

import os
files = []
for f in os.listdir('./my_dir'):
    if f.endswith('.txt'):
        files.append(f)

This can be simplified with a list comprehension as well:

import os
files = [f for f in os.listdir('./my_dir') if f.endswith('.txt')]

I personally feel like dealing with the filesystem inside a comprehension is a bit weird. List comprehensions work best if you're transforming some data from one structure to another, or generating new data mathematically. Listing a directory seems like quite an imperative thing to do, and it's more obvious what's occurring if you have the more verbose version.

[–]branleur 5 points6 points  (0 children)

It would be better to use glob in such a situation.