Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to read multiple text files from a folder in Python?(Tkinter)
Python provides powerful file handling capabilities through its built-in modules. The OS module allows you to interact with the operating system and work with files and directories efficiently.
When you need to read multiple text files from a specific folder, you can use the OS module to iterate through directory contents and process only the files with desired extensions.
Required Steps
Import the OS module
Define the directory path containing text files
Create a function to read file contents
Iterate through files and filter by extension
Read and display the contents
Example
Here's how to read multiple text files from a folder ?
import os
# Define the directory path
path = "sample_folder"
# Create sample directory and files for demonstration
os.makedirs(path, exist_ok=True)
# Create sample text files
with open(f"{path}/file1.txt", "w") as f:
f.write("Sample 1\n========\nWelcome to Tutorialspoint.\n\nYou are browsing the best resource for Online Education.")
with open(f"{path}/file2.txt", "w") as f:
f.write("Sample 2\n========\nA distributed ledger is a type of data structure which resides across multiple computer devices.\n\nDistributed ledger technology (DLT) includes blockchain technologies and smart contracts.")
def read_files(file_path):
with open(file_path, 'r') as file:
print(file.read())
print() # Add blank line between files
# Change to the target directory
os.chdir(path)
# Iterate over all files in the directory
for file in os.listdir():
if file.endswith('.txt'):
# Create the filepath of particular file
file_path = f"{os.getcwd()}/{file}"
print(f"Reading {file}:")
read_files(file_path)
Reading file1.txt: Sample 1 ======== Welcome to Tutorialspoint. You are browsing the best resource for Online Education. Reading file2.txt: Sample 2 ======== A distributed ledger is a type of data structure which resides across multiple computer devices. Distributed ledger technology (DLT) includes blockchain technologies and smart contracts.
Alternative Approach Using pathlib
You can also use the modern pathlib module for more readable code ?
from pathlib import Path
def read_multiple_files(directory_path):
path = Path(directory_path)
for txt_file in path.glob("*.txt"):
print(f"Reading {txt_file.name}:")
print(txt_file.read_text())
print("-" * 40)
# Example usage
directory = "sample_folder"
read_multiple_files(directory)
Reading file1.txt: Sample 1 ======== Welcome to Tutorialspoint. You are browsing the best resource for Online Education. ---------------------------------------- Reading file2.txt: Sample 2 ======== A distributed ledger is a type of data structure which resides across multiple computer devices. Distributed ledger technology (DLT) includes blockchain technologies and smart contracts. ----------------------------------------
Key Points
File Extension Filtering: Use
endswith('.txt')to process only text filesError Handling: Consider adding try-except blocks for file operations
Path Handling: Use
os.path.join()orpathlibfor cross-platform compatibilityResource Management: Always use
with open()to ensure proper file closure
Conclusion
The OS module provides efficient methods to read multiple text files from a directory. Use os.listdir() with file extension filtering, or consider pathlib for more modern and readable code. Always ensure proper file handling with context managers.
