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

Recommended Answers

All 3 Replies

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

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

Right. You can also do it with glob:

import glob

for filename in glob.glob("path/to/files/*"):
    do_y( filename )
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.