List Filenames and Pathnames (Python)

vegaseat 1 Tallied Votes 3K Views Share

A short look at creating lists of file names or full path names using the versatile Python module glob. Glob follows the standard wildcard protocol.

# use module glob to list filenames and pathnames
# glob takes care of upper/lower case variations
# works with Python2 and Python3

import glob
import os

# all files (full path names) in a given directory
# typical windows directory
# (change to other OS formats as needed)
directory = r"C:\Temp\*.*"
for path in glob.glob(directory):
    print( path )

print( '-'*40 )

# all files (split off file names) in a given directory
directory = r"C:\Temp\*.*"
for path in glob.glob(directory):
    dirname, filename = os.path.split(path)
    print( filename )

print( '-'*40 )

# all files (full path names) in the next level subdirectories
subdirectories = r"C:\Temp\*\*.*"
for path in glob.glob(subdirectories):
    print( path )

print( '-'*40 )

# only .txt files (full path names) in a given directory
directory_txt = r"C:\Temp\*.txt"
for path in glob.glob(directory_txt):
    print( path )

print( '-'*40 )

# only .txt and .exe files (full path names) in a given directory
directory_txt = r"C:\Temp\*.txt"
directory_exe = r"C:\Temp\*.exe"
for path in glob.glob(directory_txt) + glob.glob(directory_exe):
    print( path )

print( '-'*40 )

# only .py file names (not full path) in the working directory
for fname in glob.glob("*.py"):
    print( fname )

print( '-'*40 )

# only .py file names starting with 'f' in the working directory
for fname in glob.glob("f*.py"):
    print( fname )

print( '-'*40 )

# only .txt file names in the working directory
# sorted, case insensitive
for fname in sorted(glob.glob("*.txt"), key=str.lower):
    print( fname )
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.