[Tutor] List files in directory

Bernard Lebel python at bernardlebel.com
Sun Aug 15 22:25:24 CEST 2004


Anyone has advice on how to collect filenames from a directory? Right now
I'm using os.walk( path... ) to walk an entire directory hierarchy, so if I
print the file names well I get all filenames in AND below the current
visited directory, not just the ones in the directory:

import os

# Define root seach path
sRoot = 'C:\\__PROJETS\\bernardlebel.com\\img_remote'

# Create empty list to store collected folders
aDirs = []

# Iterate through root folder to collected folders
for oDirPaths, oDirNames, oFiles in os.walk( sRoot, True, None ):
    # Add folder to list
    aDirs.append( oDirPaths )

# Check if folders were collected
if len( aDirs ) < 1:
    print 'No folder collected.'
    # Iterate through collected folder to get files
    for oDir in aDirs:
        print '_________ Checking folder: _________ ' + oDir

        for oPaths, oDirs, oDirFiles in os.walk( oDir, True, None ):
            print oDirFiles

Basically if the root folder contains 10 files and two folders each
containing 10 files, the code above will print 30 files, then 10 files, then
10 files.

I want to print only the files contains in the currently visited directory.


More information about the Tutor mailing list