Skip to main content

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ại
current_path = os.getcwd()
print("Current directory:", current_path)   #Current directory: /Users/tinhle

# Tạo đường dẫn mới
new_path = os.path.join(current_path, "hoctienganhchuyennganh")  # Kết hợp an toàn
print("Current directory:", new_path) #Current directory: /Users/tinhle/hoctienganhchuyennganh

# Thay đổi thư mục làm việc
os.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ục
os.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ục
print("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ục
os.rename("old.txt", "new.txt")

# Xóa tập tin
os.remove("file_to_delete.txt")

# Xóa thư mục rỗng
os.rmdir("empty_folder")

# Xóa thư mục không rỗng (cần shutil)
import shutil
shutil.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 tin
shutil.copy("source.txt", "destination.txt")  # Giữ metadata
shutil.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ại
exists = os.path.exists(path)

# Phân biệt tệp/thư mục
is_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ối
timestamp = os.path.getmtime(path)
from datetime import datetime
print("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 Path
path = Path("my_folder/data.txt")

# Đọc/ghi tệp
path.write_text("Hello Python!")  # Ghi
content = path.read_text()        # Đọc

# Tạo thư mục
path.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ục
for file in Path("my_folder").glob("*.txt"):  # Tìm tất cả .txt
   print(file.name)

VI. Best Practices & Xử Lý Lỗi

  1. 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!")

  2. 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!")

  3. Sử dụng pathlib thay cho os.path để code sạch hơn (Python 3.4+).
  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 shutil
from 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

  1. Tài liệu chính thức: os
  2. Hướng dẫn pathlib
  3. Cheat sheet File I/O

Thực hành ngay:

  1. Tạo script sắp xếp tệp trong Downloads thành thư mục Images/Documents/Code.
  2. 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.