Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีลบหลายไฟล์ในไดเรกทอรีด้วย Python

ลบไฟล์เดี่ยว ใช้ os.remove:

ตัวอย่าง

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

ลบหลายไฟล์ วนลูป os.remove ลบโฟลเดอร์ทั้งหมด ใช้ shutil.rmtree:

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

ลบตาม Pattern ด้วย Regex

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))