How can I Iterate Over Files in a given Directory ?

Last Updated On Wednesday 19th Jan 2022

Python loop through files in directory.Python for each file in directory.

How to iterate over files in directory using Python?

  • If we have a massive amount of files, we can manage them within different directories
  • Directory is a Collection of files and subdirectories

using os

	import os

  • os module that gives us many beneficial ways to work with files, directories…
  • To get current Directory we use os.getcwd()
  • We use print() to print correctly

1) os.listdir()

	import os

path = 'D:Codepython'

files = []
for files in os.listdir(path):
    if files.endswith(".svg") or files.endswith(".webp"):
        print(os.path.join(directory, files))

using listdir()

  • It returns a list including the names of the listings
  • We print all the path ends with svg or webp extensions

2 ) os.scandir()

	import os

path = 'D:Codepython'
for files in os.scandir(path):
    if (files.path.endswith(".webp")
            or files.path.endswith(".svg")) and files.is_file():

using scandir()

  • Both the above list the directories instantly under a directory

3) os.walk()

	    for path in paths:
        if os.path.isdir(path):
            for dirpath, dirnames, filenames in os.walk(path):
                for filename in filenames:
                    if filename.endswith(".py"):
                        full_path = os.path.join(dirpath, filename)
                        yield full_path
            yield path

paths: list

  • A list of paths. Directories will be recursed into and .py files found will be yielded. Any non-directories will be yielded as-is.