61

Trying to remove all of the files in a certain directory gives me the follwing error:

OSError: [Errno 2] No such file or directory: '/home/me/test/*'

The code I'm running is:

import os
test = "/home/me/test/*"
os.remove(test)
nick
  • 1,090
  • 1
  • 11
  • 24
Kelvin
  • 725
  • 1
  • 6
  • 11
  • 1
    official document of os.walk does have a demo :) http://docs.python.org/library/os.html#os.walk – sunqiang Jun 25 '09 at 02:10
  • Possible duplicate of [How to delete the contents of a folder in Python?](https://stackoverflow.com/questions/185936/how-to-delete-the-contents-of-a-folder-in-python) – JayRizzo Jul 03 '19 at 20:29

13 Answers13

77

os.remove() does not work on a directory, and os.rmdir() will only work on an empty directory. And Python won't automatically expand "/home/me/test/*" like some shells do.

You can use shutil.rmtree() on the directory to do this, however.

import shutil
shutil.rmtree('/home/me/test') 

be careful as it removes the files and the sub-directories as well.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Jacob Mattison
  • 50,258
  • 9
  • 107
  • 126
24

os.remove doesn't resolve unix-style patterns. If you are on a unix-like system you can:

os.system('rm '+test)

Else you can:

import glob, os
test = '/path/*'
r = glob.glob(test)
for i in r:
   os.remove(i)
basaundi
  • 1,725
  • 1
  • 13
  • 20
18

Bit of a hack but if you would like to keep the directory, the following can be used.

import os
import shutil
shutil.rmtree('/home/me/test') 
os.mkdir('/home/me/test')
Prajwel
  • 197
  • 1
  • 8
7

Because the * is a shell construct. Python is literally looking for a file named "*" in the directory /home/me/test. Use listdir to get a list of the files first and then call remove on each one.

mamboking
  • 4,559
  • 23
  • 27
5

Although this is an old question, I think none has already answered using this approach:

# python 2.7
import os

d='/home/me/test'
filesToRemove = [os.path.join(d,f) for f in os.listdir(d)]
for f in filesToRemove:
    os.remove(f) 
b2397
  • 38
  • 6
4

This will get all files in a directory and remove them.

import os

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
dir = os.path.join(BASE_DIR, "foldername")

for root, dirs, files in os.walk(dir):
  for file in files:
    path = os.path.join(dir, file)
    os.remove(path)
Björn Böing
  • 1,662
  • 15
  • 23
3

star is expanded by Unix shell. Your call is not accessing shell, it's merely trying to remove a file with the name ending with the star

DVK
  • 126,886
  • 32
  • 213
  • 327
1

shutil.rmtree() for most cases. But it doesn't work for in Windows for readonly files. For windows import win32api and win32con modules from PyWin32.

def rmtree(dirname):
    retry = True
    while retry:
        retry = False
        try:
            shutil.rmtree(dirname)
        except exceptions.WindowsError, e:
            if e.winerror == 5: # No write permission
                win32api.SetFileAttributes(dirname, win32con.FILE_ATTRIBUTE_NORMAL)
                retry = True
tefozi
  • 5,390
  • 5
  • 38
  • 52
0

os.remove will only remove a single file.

In order to remove with wildcards, you'll need to write your own routine that handles this.

There are quite a few suggested approaches listed on this forum page.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

Please see my answer here:

https://stackoverflow.com/a/24844618/2293304

It's a long and ugly, but reliable and efficient solution.

It resolves a few problems which are not addressed by the other answerers:

  • It correctly handles symbolic links, including not calling shutil.rmtree() on a symbolic link (which will pass the os.path.isdir() test if it links to a directory).
  • It handles read-only files nicely.
Community
  • 1
  • 1
Rockallite
  • 16,437
  • 7
  • 54
  • 48
0
#python 2.7
import tempfile
import shutil
import exceptions
import os

def TempCleaner():
    temp_dir_name = tempfile.gettempdir()
    for currentdir in os.listdir(temp_dir_name):
        try:
           shutil.rmtree(os.path.join(temp_dir_name, currentdir))
        except exceptions.WindowsError, e:
            print u'Не удалось удалить:'+ e.filename
Community
  • 1
  • 1
0

To Removing all the files in folder.

import os
import glob

files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
for file in files:
    os.remove(file)
-1

Another way I've done this:

os.popen('rm -f ./yourdir')
Alex
  • 6,843
  • 10
  • 52
  • 71