介绍
每次在项目中使用vs创建完工程、写完代码或者是编译链接以后,vs都会生成一堆的obj、sdf等文件,而且特别占用电脑空间,所以为了减少空间的占用每次都要删除,特意写了一个python脚本来删除。
实现
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)
print('%s deleted' % subpath)
count += 1
os.rmdir(path)
count += 1
return count
这是一个删除指定目录以及目录下文件的函数。
def walk(path):
for item in os.listdir(path):
try:
subpath = os.path.join(path, item)
mode = os.stat(subpath)[stat.ST_MODE]
except:
s = sys.exc_info()
print("Error '%s' happended on line %d" % (s[1], s[2].tb_lineno))
pass
if stat.S_ISDIR(mode):
if item == 'Debug' or item == 'Release' or item == 'ipch':
print('Cleaning %s' % subpath)
print('%d deleted' % purge(subpath))
else:
walk(subpath)
else:
if subpath.endswith('~') or subpath.endswith(".sdf") or subpath.endswith(".suo") \
or subpath.endswith(".pdb") or subpath.endswith(".ilk") or subpath.endswith(".exp")\
or subpath.endswith(".obj") or subpath.endswith(".aps") or subpath.endswith(".ncb")\
or subpath.endswith(".idb") or subpath.endswith(".ncp") or subpath.endswith(".pch")\
or subpath.endswith(".sbr") or subpath.endswith(".tmp") or subpath.endswith(".bsc")\
or subpath.endswith(".res") or subpath.endswith(".opt") or subpath.endswith(".manifest")\
or subpath.endswith(".dep") or subpath.endswith(".map") or subpath.endswith(".plg")\
or subpath.endswith(".clw") or subpath.endswith(".bak") or subpath.endswith(".i"):
try:
os.chmod(subpath, stat.S_IREAD | stat.S_IWRITE)
os.unlink(subpath)
print('%s deleted' % subpath)
except:
print("% delete failed." % subpath)
pass
walk函数主要用来遍历输入目录,然后删除Debug,Release,ipch等目录,以及~、.sdf等文件后缀的临时文件,如果还需要删除其它目录或者其它后缀的文件,则可以直接在上面代码上直接加上。
print(sys.argv)
if len(sys.argv) != 2:
current_path = os.getcwd()
else:
current_path = sys.argv[1]
dir_name = current_path
if not os.path.exists(dir_name):
print('%s is not exists.' % dir_name)
sys.exit()
print(dir_name)
walk(dir_name)
print("delete file finish. please input any key to end.")
msvcrt.getch()
如果没有输入参数,则把脚本当前目录作为需要清理的目录。