The Wayback Machine - https://web.archive.org/web/20240717024357/https://www.geeksforgeeks.org/how-to-iterate-over-files-in-directory-using-python/
Open In App

How to iterate over files in directory using Python?

Last Updated : 17 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Directory also sometimes known as a folder are unit organizational structure in a system’s file system for storing and locating files or more folders. Python as a scripting language provides various methods to iterate over files in a directory.

Below are the various approaches by using which one can iterate over files in a directory using python:

Method 1: os.listdir()

This function returns the list of files and subdirectories present in the given directory. We can filter the list to get only the files using os.path.isfile() function:

Example:

Python3




# import required module
import os
# assign directory
directory = 'files'
 
# iterate over files in
# that directory
for filename in os.listdir(directory):
    f = os.path.join(directory, filename)
    # checking if it is a file
    if os.path.isfile(f):
        print(f)


Output:

Method 2: os.scandir()

This method is used to get an iterator of os.DirEntry objects corresponding to the entries in the directory given by specified path.

Example:

Python3




# import required module
import os
 
# assign directory
directory = 'files'
 
# iterate over files in
# that directory
for filename in os.scandir(directory):
    if filename.is_file():
        print(filename.path)


Output:

Method 3: pathlib module

We can iterate over files in a directory using Path.glob() function which glob the specified pattern in the given directory and yields the matching files. Path.glob(‘*’) yield all the files in the given directory 

Example:

Python3




# import required module
from pathlib import Path
 
# assign directory
directory = 'files'
 
# iterate over files in
# that directory
files = Path(directory).glob('*')
for file in files:
    print(file)


Output:

Method 4: os.walk()

We can also search for subdirectories using this method as it yields a 3-tuple (dirpath, dirnames, filenames).

  • root: Prints out directories only from what you specified.
  • dirs: Prints out sub-directories from the root.
  • files: Prints out all files from root and directories.

Python3




# import required module
import os
 
# assign directory
directory = 'files'
 
# iterate over files in
# that directory
for root, dirs, files in os.walk(directory):
    for filename in files:
        print(os.path.join(root, filename))


Output:

Method 5: glob module

The glob.iglob() function returns an iterator over the list of pathnames that match the given pattern.

Example:

Python3




# import required module
import glob
 
# assign directory
directory = 'files'
 
# iterate over files in
# that directory
for filename in glob.iglob(f'{directory}/*'):
    print(filename)


Output:



Similar Reads

Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over multiple lists at a time For better understanding
4 min read
Iterate over a set in Python
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements.There are numerous ways that can be used to iterate over a Set. Some of these ways provide faster time execution as compared to others. Some of these ways include, iterating using for/while loops, comprehensions, iterators and their variat
6 min read
Python - Iterate over Columns in NumPy
Numpy (abbreviation for 'Numerical Python') is a library for performing large-scale mathematical operations in a fast and efficient manner. This article serves to educate you about methods one could use to iterate over columns in an 2D NumPy array. Since a single-dimensional array only consists of linear elements, there doesn't exists a distinguish
3 min read
How to Iterate over Dataframe Groups in Python-Pandas?
In this article, we'll see how we can iterate over the groups in which a data frame is divided. So, let's see different ways to do this task. First, Let's create a data frame: C/C++ Code # import pandas library import pandas as pd # dictionary dict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # create a dataframe df = pd.DataFrame(dict) # show
2 min read
How to iterate over OrderedDict in Python?
An OrderedDict is a subclass that preserves the order in which the keys are inserted. The difference between OrderedDict and Dict is that the normal Dict does not keep a track of the way the elements are inserted whereas the OrderedDict remembers the order in which the elements are inserted. Explanation: Input : original_dict = { 'a':1, 'b':2, 'c':
2 min read
How to Iterate over months between two dates in Python?
In this article, we will discuss how to iterate over months between two dates using Python. We can iterate over months between two dates using timedelta and rrule methods. Method 1: Iteration using timedeltatimedelta() is used for calculating differences in dates and also can be used for date manipulations in Python Example: But using timedelta we
2 min read
Loop or Iterate over all or certain columns of a dataframe in Python-Pandas
Pandas DataFrames facilitate column-wise iteration, allowing convenient access to elements in each column. In this article, we will discuss how to loop or Iterate overall or certain columns of a DataFrame. Creating Pandas DataframeIn this article, we will use this Dataframe that we have created by using the Pandas package. C/C++ Code # import panda
5 min read
Iterate over a dictionary in Python
In this article, we will cover How to Iterate Through a Dictionary in Python. Dictionary in Python is a collection of data values, used to store data values like a map, unlike other Data Types that hold only a single value as an element, Dictionary holds the key: value pair in Python. To Iterate through values in a dictionary you can use built-in m
6 min read
Iterate over a list in Python
The List is equivalent to arrays in other languages, with the extra benefit of being dynamic in size. In Python , the list is a type of container in Data Structures, which is used to store multiple data at the same time. Unlike Sets , lists in Python are ordered and have a definite count. In this article, we will see how to iterate over a list in P
8 min read
How to move all files from one directory to another using Python ?
In this article, we will see how to move all files from one directory to another directory using Python. In our day-to-day computer usage we generally copy or move files from one folder to other, now let's see how to move a file in Python: This can be done in two ways:Using os module.Using shutil module.Source and Destination Folder Setup Before Ru
2 min read
Practice Tags :
three90RightbarBannerImg