Trying to remove all 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)
Trying to remove all 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)
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.
os.remove() does not work on a directory, and os.rmdir() will only work on an empty directory.
You can use shutil.rmtree() to do this, however.
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.
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)
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
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