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.
1 |
import os |
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.
1 |
folder_path = "TextFiles" |
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.
1 2 |
file_list = os.listdir(folder_path) print(file_list) |
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.
1 2 3 4 5 6 |
for file in file_list: with open(os.path.join(folder_path, file), "r") as f: content = f.read() print(f"Contents of {file}:") print(content) print("\n") |
This should output the contents of each text file:
Full Code
1 2 3 4 5 6 7 8 9 10 11 |
import os folder_path = "TextFiles" file_list = os.listdir(folder_path) for file in file_list: with open(os.path.join(folder_path, file), "r") as f: content = f.read() print(f"Contents of {file}:") print(content) print("\n") |
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.