本帖最后由 元芳你怎么看 于 2016-6-22 14:36 编辑
- #!/usr/bin/env python2
- # -*- coding: UTF-8 -*-
- # coding:utf-8
-
- '''
- 功能:保留当前目录下最新的十个文件,删除其他旧文件
- Author : Randy
- '''
-
- import string,os,os.path
-
- dir = os.getcwd() #获取脚本所在目录
- print "脚本所在的目录:%s" % dir
-
-
- def check_file():
- dir_name = os.listdir(dir) #脚本目录下的文件和目录名
- file_name = []
- length = len(dir_name)
- for i in range(length):
- if os.path.isfile(dir_name[i]) and dir_name[i].rfind('.war')>0: #判断是否是文件
- # print dir_name[i]
- file_name.append(os.path.join(dir,dir_name[i])) #循环结束后生成一个绝对路径+文件名的列表
- # print "哈哈,调用我了,我把是文件的列表发给你呀"
-
- # print "file_name的值包括:"
- # for file in file_name:
- # print file
-
- file_mtime = {}
- for file in file_name:
- mtime=os.path.getmtime(file)
- file_mtime[mtime] = file #生成一个以修改时间为键,以文件绝对路径为值的字典
-
- return file_mtime
-
-
- def check_time():
- file_mtime = check_file()
- # print "该目录下的文件:"
- # for file in file_name:
- # print "%s" % file
- print '*' * 50
-
- # file_mtime = {}
- # for file in file_name:
- # mtime=os.path.getmtime(file)
- # file_mtime[mtime] = file #生成一个以修改时间为键,以文件绝对路径为值的字典
-
- file_mtime_keys = file_mtime.keys()
- file_mtime_keys.sort(reverse=True)
- length = len(file_mtime_keys)
-
- if length>10:
- for i in range(10,length):
- print file_mtime[file_mtime_keys[i]]
- try:
- inputcontent = raw_input ("是否要删除以上文件:y/n \n")
- if inputcontent == 'y':
- for i in range(10,length):
- os.remove(file_mtime[file_mtime_keys[i]])
- elif inputcontent == 'n':
- print "程序中断"
- else:
- print '-' * 50
- print "\n请输入正确的值:(y/n)\n"
- print '-' * 50,"\n"
- check_time()
- except KeyboardInterrupt:
- print "\n 程序中断 "
- # except ValueError:
- # print "请输入正确的值:(y/n)"
- # else:
- # print '-' * 50
- # print "\n请输入正确的值:(y/n)\n"
- # print '-' * 50,"\n"
- # check_time()
-
-
- if __name__ == '__main__':
- check_time()
- # check_file()
-
复制代码
|