0% found this document useful (0 votes)
5 views2 pages

Python Lesson Folder Handling

This lesson covers folder handling in Python using the os and pathlib modules. It demonstrates how to list and read text files from a specified folder and includes a mini project for creating a simple digital library. The provided code examples illustrate the usage of both modules for file operations.

Uploaded by

dibyarayart
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Python Lesson Folder Handling

This lesson covers folder handling in Python using the os and pathlib modules. It demonstrates how to list and read text files from a specified folder and includes a mini project for creating a simple digital library. The provided code examples illustrate the usage of both modules for file operations.

Uploaded by

dibyarayart
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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')

You might also like