🐍 Ngày 34 - Python hằng ngày 365 ngày - Làm việc với thư mục và tập tin
· 2 min read
🎯 Mục tiêu
Tìm hiểu cách làm việc với thư mục và tập tin trong Python: tạo, đổi tên, xóa thư mục, kiểm tra sự tồn tại, liệt kê file,...
🧠 Kiến thức cần biết
- Dùng thư viện
os
vàshutil
để thao tác với file/folder. - Thư viện
pathlib
(từ Python 3.4) hiện đại hơn và dễ dùng hơnos
.
📦 Ví dụ: Tạo thư mục, ghi file, liệt kê và xóa
python
import os
from pathlib import Path
# Tạo thư mục
os.makedirs("./test_folder", exist_ok=True)
# Tạo file trong thư mục
with open("test_folder/hello.txt", "w", encoding="utf-8") as f:
f.write("Xin chào, Python!")
# Liệt kê file trong thư mục
files = os.listdir("test_folder")
print("📁 File trong test_folder:", files)
# Đổi tên file
os.rename("test_folder/hello.txt", "test_folder/xinchao.txt")
# Xóa file
os.remove("test_folder/xinchao.txt")
# Xóa thư mục
os.rmdir("test_folder")