Python Lesson: Folder Handling with os and pathlib
In this lesson, we'll explore how to work with folders in Python using two powerful modules: os and
pathlib. We'll learn how to list files, read files, and build a simple digital library.
1. Using os module
List all files in a folder:
import os
folder_path = 'path/to/your/folder'
files = os.listdir(folder_path)
print(files)
Read all .txt files from a folder:
import os
folder_path = 'path/to/your/folder'
for filename in os.listdir(folder_path):
if filename.endswith('.txt'):
with open(os.path.join(folder_path, filename), 'r') as file:
print(file.read())
2. Using pathlib module
List all files in a folder:
from pathlib import Path
folder = Path('path/to/your/folder')
files = list(folder.iterdir())
print(files)
Read all .txt files from a folder:
from pathlib import Path
folder = Path('path/to/your/folder')
for file in folder.glob('*.txt'):
with open(file, 'r') as f:
print(f.read())
3. Mini Project: Digital Library
This mini project lists and reads all text files like a simple digital library.
from pathlib import Path
def digital_library(folder_path):
folder = Path(folder_path)
books = list(folder.glob('*.txt'))
print("Available books:")
for i, book in enumerate(books, start=1):
print(f"{i}. {book.name}")
choice = int(input("Enter book number to read: ")) - 1
if 0 <= choice < len(books):
with open(books[choice], 'r') as file:
print(file.read())
else:
print("Invalid choice.")
digital_library('path/to/your/library')