试图删除某个目录中的所有文件给我以下错误:
OSError: [Errno 2] No such file or directory: '/home/me/test/*'
我正在运行的代码是:
import os test = "/home/me/test/*" os.remove(test)
os.remove()
在目录上不起作用,而os.rmdir()
只能在空目录下工作。 Python不会像一些shell那样自动扩展“/ home / me / test / *”。
但是,您可以在目录上使用shutil.rmtree()
来执行此操作。
import shutil shutil.rmtree('/home/me/test')
小心,因为它删除文件和子目录以及。
os.remove不能解析unix风格的模式。 如果您使用的是类Unix系统,则可以:
os.system('rm '+test)
否则你可以:
import glob, os test = '/path/*' r = glob.glob(test) for i in r: os.remove(i)
因为*是一个shell构造。 Python正在字面上在目录/ home / me / test中寻找名为“*”的文件。 首先使用listdir获取文件列表,然后调用每个文件的remove。
另一种方法,我已经这样做了:
os.popen('rm -f ./yourdir')
星星由Unix shell扩展。 你的电话没有访问shell,只是试图删除一个名字以星号结尾的文件
os.remove只会删除一个文件。
为了用通配符删除,你需要编写自己的例程来处理这个。
这个论坛页面上列出了很多建议的方法 。
shutil.rmtree()在大多数情况下。 但是它不适用于Windows只读文件。 对于Windows,从PyWin32导入win32api和win32con模块。
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
请在这里看到我的答案:
https://stackoverflow.com/a/24844618/2293304
这是一个漫长而丑陋的,但可靠和有效的解决方案。
它解决了一些其他答复者没有解决的问题:
shutil.rmtree()
os.path.isdir()
如果它链接到目录,它将通过os.path.isdir()
测试)。 #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
虽然这是一个老问题,但我认为没有人用这种方法来回答:
#python 2.7 import os filesToRemove = [f for f in os.listdir('/home/me/test')] os.remove(f) for f in files