954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Acting on Directories?

Hi, I'm a noob Python/Tkinter user, and I'm finding that gathering information on the two is not as easy as I'd like... hopefully you guys will be able to help. My first question: I was just wondering if there's a way to tell Python, "take all the files in X directory and do Y with each."

aot
Junior Poster in Training
83 posts since Feb 2007
Reputation Points: 10
Solved Threads: 1
 

Yes, there are ways to do this. Here is one:

import os

def do_y( filename ):
    print filename

for filename in os.listdir("/path/to/dir/x"):
    do_y( filename )


Regards, mawe

mawe
Junior Poster
133 posts since Sep 2005
Reputation Points: 19
Solved Threads: 58
 

Just to be clear: os.listdir() returns only the local filename, which often means that you need to attach the full path to get results:

import os

fullpath = "My/favorite/files/"
for filename in os.listdir(fullpath):
   do_y(fullpath+filename)


Jeff

jrcagle
Practically a Master Poster
608 posts since Jul 2006
Reputation Points: 92
Solved Threads: 156
 

Right. You can also do it with glob:

import glob

for filename in glob.glob("path/to/files/*"):
    do_y( filename )
mawe
Junior Poster
133 posts since Sep 2005
Reputation Points: 19
Solved Threads: 58
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You