这里有两个需求:
-
删除某个目录以及子目录下的所有.svn文件
-
删除某个文件夹下所有文件
在Python中,文件操作主要来自os模块,主要方法如下:
os.listdir(dirname):列出dirname下的目录和文件
os.getcwd():获得当前工作目录
os.curdir:返回当前目录('.')
os.chdir(dirname):改变工作目录到dirname
os.path.isdir(name):判断name是不是一个目录,name不是目录就返回false
os.path.isfile(name):判断name是不是一个文件,不存在name也返回false
os.path.exists(name):判断是否存在文件或目录name
os.path.getsize(name):获得文件大小,如果name是目录返回0L
os.path.abspath(name):获得绝对路径
os.path.normpath(path):规范path字符串形式
os.path.split(name):分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在)
os.path.splitext():分离文件名与扩展名
os.path.join(path,name):连接目录与文件名或目录
os.path.basename(path):返回文件名
os.path.dirname(path):返回文件路径
os.remove(dir) #dir为要删除的文件夹或者文件路径
os.rmdir(path) #path要删除的目录的路径。需要说明的是,使用os.rmdir删除的目录必须为空目录,否则函数出错。
删除目录下的svn代码:
Code
#!/usr/bin/env python
#coding=utf-8
import sys, os, stat
def walk(path):
for item in os.listdir(path):
subpath = os.path.join(path, item)
mode = os.stat(subpath)[stat.ST_MODE]
if stat.S_ISDIR(mode):
if item == ".svn":
print "Cleaning %s " %subpath
print "%d deleted" % purge(subpath)
else:
walk(subpath)
def purge(path):
count = 0
for item in os.listdir(path):
subpath = os.path.join(path, item)
mode = os.stat(subpath)[stat.ST_MODE]
if stat.S_ISDIR(mode):
count += purge(subpath)
else:
os.chmod(subpath, stat.S_IREAD|stat.S_IWRITE)
os.unlink(subpath)
count += 1
os.rmdir(path)
count += 1
return count
if len(sys.argv) != 2:
print "Usage: python cleansvn.py path"
sys.exit(1)
walk(sys.argv[1])
删除某目录下所有文件和文件夹:
#!/usr/bin/env python
#coding=utf-8
import sys, os, stat
def walk(path):
for item in os.listdir(path):
subpath = os.path.join(path, item)
mode = os.stat(subpath)[stat.ST_MODE]
if stat.S_ISDIR(mode):
if item == ".svn":
print "Cleaning %s " %subpath
print "%d deleted" % purge(subpath)
else:
walk(subpath)
def purge(path):
count = 0
for item in os.listdir(path):
subpath = os.path.join(path, item)
mode = os.stat(subpath)[stat.ST_MODE]
if stat.S_ISDIR(mode):
count += purge(subpath)
else:
os.chmod(subpath, stat.S_IREAD|stat.S_IWRITE)
os.unlink(subpath)
count += 1
os.rmdir(path)
count += 1
return count
if len(sys.argv) != 2:
print "Usage: python cleansvn.py path"
sys.exit(1)
walk(sys.argv[1])
Code
#!/usr/bin/env python
#coding=utf-8
import os
def delete_all_file(path):
"delete all folers and files"
if os.path.isfile(path):
try:
os.remove(path)
except:
pass
elif os.path.isdir(path):
for item in os.listdir(path):
itemsrc = os.path.join(path, item)
delete_all_file(itemsrc)
try:
os.rmdir(path)
except:
pass
if __name__ == "__main__":
dirname = r'F:\trunk'
print delete_all_file(dirname)
#!/usr/bin/env python
#coding=utf-8
import os
def delete_all_file(path):
"delete all folers and files"
if os.path.isfile(path):
try:
os.remove(path)
except:
pass
elif os.path.isdir(path):
for item in os.listdir(path):
itemsrc = os.path.join(path, item)
delete_all_file(itemsrc)
try:
os.rmdir(path)
except:
pass
if __name__ == "__main__":
dirname = r'F:\trunk'
print delete_all_file(dirname)