【发布时间】:2010-10-23 06:51:00
【问题描述】:
在 Python 中实现 rm -rf 的最简单方法是什么?
【问题讨论】:
标签: python
在 Python 中实现 rm -rf 的最简单方法是什么?
【问题讨论】:
标签: python
import shutil
shutil.rmtree("dir-you-want-to-remove")
【讨论】:
rm -rf non-existing-folder 工作正常(它没有做任何事情),但你的脚本会失败
shutil.rmtree() 是正确的答案,但看看另一个有用的函数 - os.walk()
【讨论】:
虽然有用,但 rmtree 并不等同:如果您尝试删除单个文件,它会出错,rm -f 不会(参见下面的示例)。
要解决此问题,您需要检查您的路径是文件还是目录,并采取相应措施。像这样的东西应该可以解决问题:
import os
import shutil
def rm_r(path):
if os.path.isdir(path) and not os.path.islink(path):
shutil.rmtree(path)
elif os.path.exists(path):
os.remove(path)
注意:此函数不会处理字符或块设备(需要使用stat 模块)。
rm -f 和 Python 的 shutils.rmtree 之间的区别示例
$ mkdir rmtest
$ cd rmtest/
$ echo "stuff" > myfile
$ ls
myfile
$ rm -rf myfile
$ ls
$ echo "stuff" > myfile
$ ls
myfile
$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import shutil
>>> shutil.rmtree('myfile')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/shutil.py", line 236, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/usr/lib/python2.7/shutil.py", line 234, in rmtree
names = os.listdir(path)
OSError: [Errno 20] Not a directory: 'myfile'
编辑: 处理符号链接;根据@pevik 的评论注意限制
【讨论】:
os.path.isdir(symlink_to_directory) 上返回 True
os.remove 删除设备就好了;我刚试过。我不明白有关代码不适用于设备文件等的评论。 POSIX 系统调用unlink 不区分文件和设备。
import os
import shutil
def rm_r(path):
if not os.path.exists(path):
return
if os.path.isfile(path) or os.path.islink(path):
os.unlink(path)
else:
shutil.rmtree(path)
略微改进了加布里埃尔格兰特的版本。这也适用于目录的符号链接。 注意:函数不处理 Un*x 字符和块设备(它需要使用stat 模块)。
【讨论】:
unlink 放入后备案例来处理设备;如果检测到目录,请执行rmtree。 IE。我们不必专门测试设备节点类型。
这样做:
import os
dirname = "path_to_directory_to_remove"
os.system("rm -rf %s" % dirname)
【讨论】:
def delite(filepath):
import os, stat, sys
def intertwin(_list):
list1 = []
for i in _list:
list1 += i
return list1
allpath = os.walk(filepath)
walk = []
dirs = []
path = []
allfiles = []
for i in allpath:
walk.append(i)
for i in walk:
dirs.append(i[0])
for _dir in dirs:
os.chdir(_dir)
files = os.listdir(_dir)
files1 = []
for i in files:
files1.append(_dir + '\\' + i)
files = files1[:]
allfiles.append(files)
allfiles = intertwin(allfiles)
for i in allfiles:
os.chmod(i, stat.S_IRWXU)
allfiles.reverse()
os.chdir(sys.path[0])
for i in allfiles:
try:
os.remove(i)
except:
try:
os.rmdir(i)
except:
pass
os.chmod(filepath, stat.S_IRWXU)
try:
os.remove(filepath)
except:
os.rmdir(filepath)
allfiles.reverse()
os.chdir(sys.path[0])
for i in allfiles:
try:
os.remove(i)
except:
try:
os.rmdir(i)
except:
pass
os.chmod(filepath, stat.S_IRWXU)
try:
os.remove(filepath)
except:
os.rmdir(filepath)
【讨论】:
阻止删除文件的 Windows 解决方法是截断文件:
outputFile = open(r"filename.txt","w")
outputFile.truncate()
outputFile.close()
outputFile = open(r"filename.txt","a+")
【讨论】: