How can I iterate over files in a given directory? How can I iterate over files in a given directory? python python

How can I iterate over files in a given directory?


Original answer:

import osfor filename in os.listdir(directory):    if filename.endswith(".asm") or filename.endswith(".py"):          # print(os.path.join(directory, filename))        continue    else:        continue

Python 3.6 version of the above answer, using os - assuming that you have the directory path as a str object in a variable called directory_in_str:

import osdirectory = os.fsencode(directory_in_str)    for file in os.listdir(directory):     filename = os.fsdecode(file)     if filename.endswith(".asm") or filename.endswith(".py"):          # print(os.path.join(directory, filename))         continue     else:         continue

Or recursively, using pathlib:

from pathlib import Pathpathlist = Path(directory_in_str).glob('**/*.asm')for path in pathlist:     # because path is object not string     path_in_str = str(path)     # print(path_in_str)
  • Use rglob to replace glob('**/*.asm') with rglob('*.asm')
    • This is like calling Path.glob() with '**/' added in front of the given relative pattern:
from pathlib import Pathpathlist = Path(directory_in_str).rglob('*.asm')for path in pathlist:     # because path is object not string     path_in_str = str(path)     # print(path_in_str)


This will iterate over all descendant files, not just the immediate children of the directory:

import osfor subdir, dirs, files in os.walk(rootdir):    for file in files:        #print os.path.join(subdir, file)        filepath = subdir + os.sep + file        if filepath.endswith(".asm"):            print (filepath)


You can try using glob module:

import globfor filepath in glob.iglob('my_dir/*.asm'):    print(filepath)

and since Python 3.5 you can search subdirectories as well:

glob.glob('**/*.txt', recursive=True) # => ['2.txt', 'sub/3.txt']

From the docs:

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched.