Bài 10 - Quản Lý Thư Mục và Tập Tin trong Python
. Giới thiệu
Trong Python, quản lý thư mục và tập tin là kỹ năng cốt lõi khi làm việc với hệ thống tệp. Các thư viện chính:
os: Thao tác cơ bản (tạo, xóa, đổi tên...).shutil: Thao tác nâng cao (sao chép, di chuyển cây thư mục).pathlib(Python 3.4+): Quản lý đường dẫn hướng đối tượng.
II. Các Thao Tác Cơ Bản với os
1. Làm việc với đường dẫn
import os
# Lấy đường dẫn hiện tạicurrent_path = os.getcwd()print("Current directory:", current_path) #Current directory: /Users/tinhle
# Tạo đường dẫn mớinew_path = os.path.join(current_path, "hoctienganhchuyennganh") # Kết hợp an toànprint("Current directory:", new_path) #Current directory: /Users/tinhle/hoctienganhchuyennganh
# Thay đổi thư mục làm việcos.chdir("/path/to/new/directory")
2. Tạo thư mục
Giờ bạn kiểm tra
print(os.path.exists(new_path)) #False
# Tạo 1 thư mụcos.mkdir(new_path)
print(os.path.exists(new_path)) #True
# Tạo thư mục lồng nhau (tạo cả cấp cha nếu cần)os.makedirs("parent/child/grandchild", exist_ok=True) # exist_ok=True: bỏ qua lỗi nếu đã tồn tại
3. Liệt kê nội dung thư mục
items = os.listdir("my_folder") # Trả về list tên tệp/thư mụcprint("Items in directory:", items)
# Liệt kê kèm đường dẫn đầy đủfull_paths = [os.path.join("my_folder", item) for item in items]
4. Đổi tên/Xóa tệp & thư mục
# Đổi tên tập tin/thư mụcos.rename("old.txt", "new.txt")
# Xóa tập tinos.remove("file_to_delete.txt")
# Xóa thư mục rỗngos.rmdir("empty_folder")
# Xóa thư mục không rỗng (cần shutil)import shutilshutil.rmtree("non_empty_folder") # Xóa cả nội dung bên trong!
III. Thao Tác Nâng Cao với shutil
1. Sao chép
import shutil
# Sao chép tập tinshutil.copy("source.txt", "destination.txt") # Giữ metadatashutil.copy2("source.txt", "backup/") # Giữ nguyên metadata + thời gian
# Sao chép thư mục (toàn bộ nội dung)shutil.copytree("source_folder", "backup_folder")
2. Di chuyển
shutil.move("old_location/file.txt", "new_location/") # Di chuyển tệp/thư mục
IV. Kiểm Tra Thuộc Tính với os.path
path = "my_folder/file.txt"
# Kiểm tra tồn tạiexists = os.path.exists(path)
# Phân biệt tệp/thư mụcis_file = os.path.isfile(path)is_dir = os.path.isdir(path)
# Lấy kích thước tệp (bytes)size = os.path.getsize(path)
# Lấy thời gian sửa đổi cuốitimestamp = os.path.getmtime(path)from datetime import datetimeprint("Last modified:", datetime.fromtimestamp(timestamp))
V. Quản Lý Đường Dẫn Hiện Đại với pathlib
from pathlib import Path
# Tạo đối tượng Pathpath = Path("my_folder/data.txt")
# Đọc/ghi tệppath.write_text("Hello Python!") # Ghicontent = path.read_text() # Đọc
# Tạo thư mụcpath.parent.mkdir(parents=True, exist_ok=True) # Tạo thư mục cha nếu cần
# Lặp qua tệp trong thư mụcfor file in Path("my_folder").glob("*.txt"): # Tìm tất cả .txt print(file.name)
VI. Best Practices & Xử Lý Lỗi
Luôn kiểm tra tồn tại trước khi thao tác:
if not os.path.exists("important.txt"):print("File not found!")Xử lý ngoại lệ:
try:os.remove("file.txt")except FileNotFoundError:print("File does not exist.")except PermissionError:print("You don't have permission!")- Sử dụng
pathlibthay choos.pathđể code sạch hơn (Python 3.4+). - Cẩn thận với
shutil.rmtree()– Xóa vĩnh viễn không thể khôi phục!
VII. Ví Dụ Tổng Hợp: Tạo Backup Thư Mục
import shutilfrom datetime import datetime
def backup_folder(source, dest_root): timestamp = datetime.now().strftime("%Y%m%d_%H%M") dest = Path(dest_root) / f"backup_{timestamp}" shutil.copytree(source, dest) print(f"Backup created at: {dest}")
backup_folder("/data/project", "/backups")
VIII. Tài Nguyên Học Tập
Thực hành ngay:
- Tạo script sắp xếp tệp trong Downloads thành thư mục Images/Documents/Code.
- Viết tool sao lưu hàng tuần tự động sử dụng
cron(Linux) hoặc Task Scheduler (Windows).
Các từ tiếng anh chuyên ngành:
Python directory - Thư mục Python
File Management System - Hệ thống quản lý thư mục
CWD - Current working directory - thư mục đang làm việc.