How to Open All the Files in a Directory in Python?

Python supports various modules and functions used for file manipulation. Various operations are performed on the files using these functions, such as opening, showing, reading, updating, etc. To open all the files in a defined directory, functions such as “os.listdir()”, “glob()”, etc., are utilized along with the “open()” function in Python.

Various methods are used in Python to open all the listed files in a specific directory. The methods given below are explained in this Python blog:

Method 1: Using os.listdir() Function

The “os.listdir()” function is used to get the list of all files present in the given directory. In the example code given below, the “os.listdir()” function is used to open all the files in a directory:

The following files are present in Python’s current working directory:

Code:

import os
for file_name in os.listdir(os.getcwd()):
   with open(os.path.join(os.getcwd(), file_name), 'r') as f:
       content= f.read()
       print(content)

In the above code:

  • The “os.listdir()” function is utilized to get all the files from the defined directory.
  • The “os.getcwd()” function is used to get the current working directory, and the value is passed as an argument to the “os.listdir()” function.
  • In the above code, the “os.getcwd()” function is utilized to get the specific path of the existing directory. However, you can specify the directory path of your own choice instead of specifying the current one.
  • All the files are opened using the “open()” function in read mode and printed on screen using the “read()” function.

Output:

The above output shows the text of each file in the directory.

Method 2: Using glob.glob() Function

The “glob()” function of the “glob” module is used to display all the files of the specified paths in Python. In the example below, this function is used along with the “open()” function to open the file in Python:

The following files are present in the specified directory:

Code:

import os
import glob
directory_path = 'C:/Users/p/Downloads/new'

for fname in glob.glob(os.path.join(directory_path, '*.txt')):
   with open(os.path.join(os.getcwd(), fname), 'r') as f:
       content = f.read()
       print(content)

In the above code:

  • The specified path of the directory is defined and stored in a variable “directory_path”.
  • The “for” loop is used to iterate over the specified path and get all the files having the “.txt” extension.
  • The “open()” function is used to open all the files in reading mode “r” that is found in the specified directory.

Output:

The above output shows the text of each file in the directory.

Method 3: Using os.walk() Function

The “os.walks()” function is used to list all the filenames in the specified directory. In the example given below, the “os.walks()” function is used to list all the file names:

Code:

import os
for (root, dirs, file) in os.walk('C:/Users/p/Downloads/new'):
    for filename in file:
        if '.txt' in filename:
            print(filename)

In the above code:

  • The os.walk function will retrieve all the files present in the directory named “new”.
  • Next, the for loop is utilized to iterate over all the files retrieved by the os.walks() function.
  • The nested “for” loop is utilized to iterate over the specified directory and return all the “.txt” files if it was found in the given directory.

Output:

The above output shows all the “.txt” files in the defined directory. To open these files, use the “os.walk()” function along with the “open()” function. Let’s understand it via the following code:

Code:

import os
for dirp, dir_names, file in os.walk('C:/Users/p/Downloads/new'):
    for file_name in file:
        path = os.path.join(dirp, file_name)
        with open(path, 'r') as f:
            print(f.read())

In the above code:

  • The “open()” function is used to open all the files that exist in the defined directory.
  • The “f.read()” function reads all the file content found in each file.

Output:

The above output shows the text of each file.

Method 4: Using os.scandir() Function

In the example given below, the “os.scandir()” function is used to get all the files in the given directory:

Code:

import os
dir_path = os.scandir("C:/Users/p/Downloads/new")
for file in dir_path:
    if file.is_dir() or file.is_file():
        print(file.name)

In the above code:

  • The “os.scandir()” function is used to accept the directory path and stored in a variable “dir_path”.
  • The for loop iterates over the path and returns the present file or directory.

Output:

The above output shows two files in the given directory “/new”. You can use the “os.scandir()” function with the open() function to see the content of all files.

Method 5: Using pathlib Module

In the example given below, the “pathlib” module lists all the files in a directory Python:

Code:

import pathlib
dir_path = pathlib.Path("C:/Users/p/Downloads/new")
for file in dir_path.iterdir():
    if file.is_file():
        print(file)

In the above code:

  • The “pathlib.Path()” function takes the specified path location as an argument.
  • The “for” loop iterates over the path by using the “iterdir()” function, which will iterate all entries of the directory.
  • The “file.is_file()” is utilized to check whether the entry is a file. If the found entry is a file, then the print() function displays its name on the screen.

Output:

The above output shows the files in the specified directory.

Conclusion

In Python, the “os.listdir()”, “glob.glob()”, “os.walk()”, “os.scandir()”, “pathlib.path()” functions are used with the open() function to open all the files in the directory. The “os” module functions such as “os.listdir()”, “os.walk()” and “os.scandir()” are used to list all the files of the specified directory and open the file using the “open()” function. This article delivered a thorough guide on how to open all the files in a directory in Python.