Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a file by extension in Python?

Tags:

python

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.

like image 681
stephan Avatar asked Sep 29 '15 02:09

stephan


People also ask

How do I delete a file with a specific extension?

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.

How do you delete a file with a specific name in Python?

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.


1 Answers

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)) 
like image 179
idjaw Avatar answered Oct 14 '22 10:10

idjaw