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 = [Link](folder_path)
print(files)
Read all .txt files from a folder:
import os
folder_path = 'path/to/your/folder'
for filename in [Link](folder_path):
if [Link]('.txt'):
with open([Link](folder_path, filename), 'r') as file:
print([Link]())
2. Using pathlib module
List all files in a folder:
from pathlib import Path
folder = Path('path/to/your/folder')
files = list([Link]())
print(files)
Read all .txt files from a folder:
from pathlib import Path
folder = Path('path/to/your/folder')
for file in [Link]('*.txt'):
with open(file, 'r') as f:
print([Link]())
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([Link]('*.txt'))
print("Available books:")
for i, book in enumerate(books, start=1):
print(f"{i}. {[Link]}")
choice = int(input("Enter book number to read: ")) - 1
if 0 <= choice < len(books):
with open(books[choice], 'r') as file:
print([Link]())
else:
print("Invalid choice.")
digital_library('path/to/your/library')