import os if os.path.isfile("test.txt"): os.remove("test.txt") else: print("File does not exist")
删除特定扩展名的所有文件
1 2 3 4 5 6
import os from os import listdir my_path = 'C:\\Python Pool\\Test' for file_name in listdir(my_path): if file_name.endswith('.txt'): os.remove(my_path + file_name)
删除文件夹内的所有文件
1 2 3 4
import os, glob for file in glob.glob("pythonpool/*"): os.remove(file) print("Deleted " + str(file))
删除文件夹的示例
使用shutil.rmtree()删除非空文件夹
1 2 3 4 5 6
import shutil import os location = "E:/Projects/PythonPool/" dir = "Test" path = os.path.join(location, dir) shutil.rmtree(path)
使用pathlib.Path.rmdir()删除空文件夹
1 2 3
from pathlib import Path q = Path('foldername') q.rmdir()
核心代码
通用的删除函数
1 2 3 4 5 6 7 8 9 10 11
import os import shutil
defremove(path): """ param <path> could either be relative or absolute. """ if os.path.isfile(path) or os.path.islink(path): os.remove(path) # remove the file elif os.path.isdir(path): shutil.rmtree(path) # remove dir and all contains else: raise ValueError("file {} is not a file or dir.".format(path))
处理删除文件或文件夹时避免TOCTOU问题的函数
1 2 3 4 5 6 7 8 9
import os import shutil
defremove_file_or_dir(path: str) -> None: """ Remove a file or directory """ try: shutil.rmtree(path) except NotADirectoryError: os.remove(path)