View Full Version : python os.walk question

09 September 2010, 05:40 AM
I am using the code below to iterate through a series of data files in a specified folder, and selected nodes in Maya.

The function works on lists of data files and objects.

for subdir, dirs, files in os.walk(rootdir):

How can I filter so that the resulting list of data files only contains files that end in .txt? My current list contains a .DS_Store looks like:


I want:


09 September 2010, 06:53 AM
Just one possibilty :)

origList = ['.DS_Store','data1.txt','data2.txt']
newList = []

for each in origList:
if each.endswith('txt'):

print newList

09 September 2010, 09:11 AM
hey Guido, it's python, there's bound to be at least 6 more possibilities! :D ;)

this is essentially exactly the same as guidos solution, but uses a list comprehension so it's more "pythonic"
txtFiles = [item for item in files if item.endswith('.txt')]:nathaN

09 September 2010, 09:38 AM
I prefer the legibility :eek:

When it comes to nested list comprehensions its getting really really ugly :argh:

09 September 2010, 01:48 AM
That works. Both really nice solutions, Thank you both!

CGTalk Moderation
09 September 2010, 01:48 AM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.