Bạn có thể xóa một file đơn lẻ hoặc thư mục rỗng bằng các hàm trong module os.
Ví dụ
Ví dụ, nếu muốn xóa file my_file.txt:
>>> import os
>>> os.remove('my_file.txt')
Tham số của os.remove phải là đường dẫn tuyệt đối hoặc tương đối.
Để xóa nhiều file, chỉ cần lặp qua danh sách file và dùng hàm trên. Nếu muốn xóa thư mục chứa tất cả file cần xóa, bạn có thể xóa thư mục và tạo lại như sau:
>>> import shutil
>>> shutil.rmtree('my_folder')
>>> import os
>>> os.makedirs('my_folder')
Bạn cũng có thể xóa đệ quy các file bằng os.walk().
Ví dụ
import os, re, os.path
mypath = "my_folder"
for root, dirs, files in os.walk(mypath):
for file in files:
os.remove(os.path.join(root, file))
Cấu trúc thư mục sẽ được giữ nguyên nếu dùng phương pháp trên.