python删除文件一行数据、不使用临时文件_python删除临时文件

介绍

每次在项目中使用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()

如果没有输入参数,则把脚本当前目录作为需要清理的目录。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值