0

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."

3
Contributors
3
Replies
4
Views
10 Years
Discussion Span
Last Post by mawe
0

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

0

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

0

Right. You can also do it with glob:

import glob

for filename in glob.glob("path/to/files/*"):
    do_y( filename )
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.