All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Read All Files In A Directory Python

Last Updated : Mar 11, 2024

Read All Files In A Directory Python

In this article we will show you the solution of read all files in a directory python, the Python os or pathlib modules can be used to read every file in a directory.

These modules offer ways to open a directory's files for reading and to list the files within it.

It's a typical task in data processing and file handling. Now let's talk about the Python idea of reading every file in a directory.

Step By Step Guide On Read All Files In A Directory Python :-

Method - Using a for loop and open() function

import os
os.chdir("path/to/directory")
file_list = os.listdir()
for file_name in file_list:
    with open(file_name, "r") as file:
        contents = file.read()
        print(f"Contents of {file_name}:")
        print(contents)
  1. You can see that we used the for loop and open function to construct Python code that reads every file in a directory.
  2. To work with file paths and directories, we first import the os module.
  3. The working directory is set to the directory holding the files we want to read using the os.chdir() function.
  4. The directory is specified in this example using a relative path, but you can also use an absolute path.
  5. To obtain a list of every file in the directory, we utilise the os.listdir() function. A string list of filenames is what this function returns.
  6. A list of filenames is iterated over using a for loop.
  7. We open each file individually using with the open() statement, which guarantees that the file will be closed once we are finished reading it.
  8. By supplying "r" as the second option to open, we express that we wish to open the file in read-only mode ().
  9. Using the file, we read the file's content.
  10. The file's contents are returned as a string by the read() method.
  11. With the print() function, we output the file's name and contents to the console.

Method - Using the pathlib module:

from pathlib import Path
path = Path("path/to/directory")
for file in path.iterdir():
    if file.is_file():
        with file.open("r") as f:
            contents = f.read()
            print(f"Contents of {file.name}:")
            print(contents)
  1. Below, you can see how we used the pathlib module to construct Python code that reads every file in a directory.
  2. The Path class is first imported from pathlib module. Working with file paths & directories can be done object-orientedly with this class.
  3. The directory holding the files we wish to read is represented by a Path object, which is created. The directory is specified in this example using a relative path, but you can also use an absolute path.
  4. To obtain a list of all the files and folders in the directory, we utilise the Path object's iterdir() method. Iterator objects that can be looped over are returned by this method.
  5. Checking whether the item with in iterator is a file is done using an if statement (as opposed to a directory). Because iterdir() gives both files and directories, this is necessary.
  6. We use the with file command to open the item if it is a file.
  7. open() command. This makes sure that once we're done reading a file, it is closed. By supplying "r" as the second option to open, we express that we wish to open the file in read-only mode ().
  8. The f.read() method is used to read the file's contents, and it returns the data as a string.
  9. With the print() function, we output the file's name and contents to the console.

Conclusion :-

As a result, we have successfully mastered the Python idea of reading all files in a directory.

We also discovered that reading every file in a directory in Python is a typical activity that may be completed in a number of different ways.

Working with directories & file paths can be facilitated by the os module as well as the pathlib module.

I hope this article on read all files in a directory python helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Dikshita

Passionate Electronics and Communication Engineering student with expertise in web development (HTML, CSS, JS,PHP, Bootstrap, React.js) and content writing. Eager problem solver and tech enthusiast, adept at creating engaging web experiences.

Follow Dikshita On Linkedin 🡪