How To Read Multiple Text Files From Folder In Python

In this tutorial, we’ll learn how to read multiple text files from a folder in Python. Reading multiple text files can be useful in various applications, such as data analysis, natural language processing, or simply organizing and manipulating text data.

We’ll be using the os module to access the file system and the built-in open() function to read the contents of each text file.

To illustrate, let’s consider we have a folder named ‘TextFiles’ containing the following text files:

  • file1.txt
  • file2.txt
  • file3.txt

Sample content of these files could be:

file1.txt

This is file1

file2.txt

This is file2

file3.txt

This is file3

Now, let’s begin our tutorial.

Step 1: Import Required Modules

First, we will need to import the os module, which provides a way of interacting with the file system.

Step 2: Define Folder Path

Define the path for the folder containing the text files. In this tutorial, our folder is named ‘TextFiles’ and is located in the same directory as the Python script.

Step 3: Get a List of Files in the Folder

Now, we’ll use the os.listdir() function to get the list of files in the folder.

This should output the list of file names in the folder:

['file1.txt', 'file2.txt', 'file3.txt']

Step 4: Read Each File and Print its Contents

Now that we have the list of text files, we’ll loop through them and read their contents using the built-in open() function. After reading, we’ll print the contents of each file.

This should output the contents of each text file:

Full Code

Output

Contents of file1.txt:
This is file1

Contents of file2.txt:
This is file2

Contents of file3.txt:
This is file3

Conclusion

In this tutorial, we have learned how to read multiple text files from a folder in Python. We have used the os module to interact with the file system and the built-in open() function to read the contents of each text file. With this knowledge, you can now easily read and process multiple text files in your Python projects.