I was messing around just trying to make a script that deletes items by ".zip" extension.
import sys import os from os import listdir test=os.listdir("/Users/ben/downloads/") for item in test: if item.endswith(".zip"): os.remove(item)
Whenever I run the script I get:
OSError: [Errno 2] No such file or directory: 'cities1000.zip'
cities1000.zip is obviously a file in my downloads folder.
What did I do wrong here? Is the issue that os.remove requires the full path to the file? If this is the issue, than how can I do that in this current script without completely rewriting it.
To remove files with a specific extension, we use the 'rm' (Remove) command, which is a basic command-line utility for removing system files, directories, symbolic links, device nodes, pipes, and sockets in Linux. Here, 'filename1', 'filename2', etc. are the names of the files including full path.
Running the Python Program File If one wants to delete all the files in the specific directory, they can use the os. rmdir() or shutil. rmtree() to delete all the files and folders in the specified directory.
You can set the path in to a dir_name
variable, then use os.path.join
for your os.remove
.
import os dir_name = "/Users/ben/downloads/" test = os.listdir(dir_name) for item in test: if item.endswith(".zip"): os.remove(os.path.join(dir_name, item))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With