清空目录中的所有文件

62

尝试删除某个目录中的所有文件时,出现以下错误:

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

我运行的代码是:

import os
test = "/home/me/test/*"
os.remove(test)

1
官方文档中的os.walk确实有演示示例 :) http://docs.python.org/library/os.html#os.walk - sunqiang
可能是重复的问题,参见 如何在Python中删除文件夹的内容? - JayRizzo
13个回答

78

os.remove() 无法删除目录,os.rmdir() 只能删除空目录。而 Python 不会自动扩展类似于一些 shell 的 "/home/me/test/*"。

你可以使用 shutil.rmtree() 来删除整个目录。

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

请小心,因为它会删除文件和子目录


2
import shutil; shutil.rmtree('/home/me/test') 导入shutil库;shutil.rmtree('/home/me/test') - Heikki Toivonen
40
请注意,使用shutil.rmtree()函数也会删除给定路径末尾的文件夹(它不仅删除目录内容,还会删除整个目录)。 - James
这并没有解释为什么 os.remove 不接受 /home/me/test/*。我已经编辑了答案。 - Jean-François Fabre
这个答案是不正确的,因为它没有保留已清空的目录。 - Jean-Pierre Schnyder

24

os.remove无法解析Unix风格的模式。如果您在类Unix系统上,则可以执行以下操作:

os.system('rm '+test)

否则,您可以:

import glob, os
test = '/path/*'
r = glob.glob(test)
for i in r:
   os.remove(i)

os.system有很多注意事项,包括不解析glob模式(因为它只是将行传递给shell);glob返回目录以及文件(os.remove无法处理)。 - Roger Pate
到目前为止最佳答案: - Jean-François Fabre

18

这有点像 hack,但如果你想保留目录,可以使用以下方法。


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

7

因为*是一个shell构造。Python实际上在目录/home/me/test中寻找名为“*”的文件。首先使用listdir获取文件列表,然后对每个文件调用remove。


5

虽然这个问题比较老了,但我认为还没有人使用这种方法来回答:

# 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) 

3
使用os.remove()函数时需要包含文件的完整路径,因此要执行os.remove(os.path.join("/home/me/test", f))以使其正常工作。 - deef
加上行 os.remove(f) for f in files 不是有效的语法。并不是所有东西都使用推导式。 - Jean-François Fabre
我非常喜欢这个答案,使用了 os 调用。我已经将其作为我的工作基础:filesToRemove = [f for f in os.listdir(self.my_folder)] for f in filesToRemove: os.remove(os.path.join(self.my_folder, f))(需要缩进)。 - wmorrison365
如果我想使用相对路径怎么办?请帮忙。 - DJ_Stuffy_K
@deef - 我进行了重构以包含该要求。 - monojohnny
@Jean-FrançoisFabre - 重构以使用标准的Python迭代。 - monojohnny

4
这将获取目录中的所有文件并删除它们。
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)

3

星号在Unix shell中被扩展。你的调用并没有访问shell,它只是试图删除以星号结尾的文件。


1

对于大多数情况,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

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

0
请看我的回答:

https://dev59.com/5nVC5IYBdhLWcg3wykQt#24844618

这是一个冗长而丑陋,但可靠高效的解决方案。

它解决了其他答案未能解决的一些问题:

  • 它正确处理符号链接,包括不对符号链接调用shutil.rmtree()(如果符号链接指向目录,则会通过os.path.isdir()测试)。
  • 它很好地处理只读文件。

1
在这种情况下,最好的方法是标记为重复。 - Jean-François Fabre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接