PDA

View Full Version : python os.walk question


misterwolfy
09-22-2010, 06: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:


['.DS_Store','data1.txt','data2.txt']


I want:


['data1.txt','data2.txt']

GiantG
09-22-2010, 07:53 AM
Just one possibilty :)

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

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

print newList

NaughtyNathan
09-22-2010, 10: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

GiantG
09-22-2010, 10:38 AM
@Nathan
I prefer the legibility :eek:

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

misterwolfy
09-23-2010, 02:48 AM
That works. Both really nice solutions, Thank you both!

CGTalk Moderation
09-23-2010, 02: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.