0

I wrote code to detect all the .exe files in a directory but instead it deletes everything in the folder. How can I change the code to make it delete only the .exe files?

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)
Woody1193
  • 7,252
  • 5
  • 40
  • 90
Axsor
  • 69
  • 6
  • 2
    Because `rmtree` deletes a directory and all it's contents. Did you mean to use `remove()`Does this [answer](https://stackoverflow.com/a/6996628/1935238) help? – DaveStSomeWhere Apr 22 '20 at 23:44

2 Answers2

2

You can only delete directories with shutil.rmtree but not files (See https://docs.python.org/3/library/shutil.html#shutil.rmtree).

You should use pathlib or os instead.

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

pathlib.Path(f'{dir_name}/{files}').unlink()
mattefrank
  • 231
  • 1
  • 9
2

shutil.rmtree removes the entire directory specified by its first argument. The second argument to shutil.rmtree is ignore_errors, telling the function whether to ignore errors that occur. It is not a file to remove.

shutil.rmtree is a completely inappropriate tool for the job you want to do. You need something like os.remove.

user2357112
  • 260,549
  • 28
  • 431
  • 505