我制作了此代码来检测文件夹中的.exe文件,但它删除了该文件夹中的所有内容。如何使它仅删除.exe文件?
import os
import shutil
dir_name = "/Users/plapl/Downloads/"
source = os.listdir("/Users/plapl/Downloads/")
for files in source:
if files.endswith(".exe"):
shutil.rmtree(dir_name, files)
您只能删除带有shutil.rmtree
的目录,而不能删除文件(请参阅https://docs.python.org/3/library/shutil.html#shutil.rmtree)。
您应该改用pathlib
或os
。
os.rmdir(f'{dir_name}/{files}')
pathlib.Path(f'{dir_name}/{files}').unlink()