How to read multiple text files from folder in Python?

Published on Aug. 22, 2023, 12:15 p.m.

To read multiple text files from a folder in Python, you can use the os module to get a list of all files in the specified directory, and then read each file using the built-in open function. Here’s an example:

import os

dir_path = '/path/to/folder'
files = os.listdir(dir_path)

for filename in files:
    if filename.endswith('.txt'):
        file_path = os.path.join(dir_path, filename)
        with open(file_path, 'r') as f:
            text = f.read()
            # Do something with the text

In this example, we first use os.listdir() to get a list of all files in the specified directory. We then loop through each file and check if it ends with the “.txt” extension. If it does, we construct the full file path using os.path.join() and open the file using open() with the ‘r’ mode (for reading). We then read the content of the file using read() and do something with the text.

You can modify this code to suit your specific needs, such as changing the directory path, filtering files by a different extension, or processing the text in a different way.

Tags:

related content