为什么我的代码删除文件夹中的所有内容?

问题描述 投票:0回答:1

我制作了此代码来检测文件夹中的.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)
python python-3.x pycharm
1个回答
0
投票

您只能删除带有shutil.rmtree的目录,而不能删除文件(请参阅https://docs.python.org/3/library/shutil.html#shutil.rmtree)。

您应该改用pathlibos

os.rmdir(f'{dir_name}/{files}')

pathlib.Path(f'{dir_name}/{files}').unlink()
© www.soinside.com 2019 - 2024. All rights reserved.