Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách xóa nhiều file trong thư mục Python?


Xóa file đơn lẻ hoặc thư mục rỗng bằng hàm module os.

Ví dụ

Xóa file my_file.txt:

>>> import os
>>> os.remove('my_file.txt')

Tham số os.remove là đường dẫn tuyệt đối/tương đối.

Xóa nhiều file, lặp list file dùng hàm trên. Muốn xóa thư mục chứa file, xóa thư mục:

>>> import shutil
>>> shutil.rmtree('my_folder')

Ví dụ

Dùng regex xóa file khớp pattern:

import os, re, os.path
pattern = "^your_regex_here$"
mypath = "my_folder"
for root, dirs, files in os.walk(mypath):
    for file in filter(lambda x: re.match(pattern, x), files):
        os.remove(os.path.join(root, file))