代码改变世界

遍历本地文件个数及创建、修改时间

2017-10-11 23:18  hdwen  阅读(300)  评论(0编辑  收藏  举报
 1 # @Author: Hdwen
 2 # @Date  : 2017/10/11 19:53
 3 # @Desc  :遍历文件或者文件夹中文件创建时间和修改时间,能够将隐藏的文件也遍历出来,如果只是遍历文件个数,则去除print()语句会节省很多时间
 4 """
 5 可以根据这个来写一个遍历文件最近七天使用过的的文件
 6 只需要判断时间:将目前的时间减去七天的时间,如果True则返回文件
 7 或者找到计算机中和什么文件名相关的文件输出它的位置,如python
 8 
 9 ((((((os.stat(path)获取文件信息包括文件大小,创建时间,修改时间等))))))
10 """
11 import time,os
12 # cwp=os.path.abspath('.')#获取当前文件位置
13 #初始化文件位置
14 path=r'G:\Download'
15 #初始化count=0,开始计数文件个数
16 count=0
17 start_time=time.clock()
18 def dir_path(path):
19     global count
20     if os.path.isdir(path):
21         for file in os.listdir(path):
22             file_path=os.path.join(path,file)
23             #判断如果是文件夹则回掉自身,否则是文件则输出
24             if os.path.isdir(file_path):
25                 dir_path(file_path)
26             else:
27                 count+=1
28                 print(count)
29                 ctime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getctime(file_path)))
30                 mtime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getmtime(file_path)))
31                 # atime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getatime(file_path)))#上次访问时间
32 
33                 print(file, 'createTime:%s'%ctime,'modifyTime:%s'% mtime)
34     else:
35         count+=1
36         print(count)
37         ctime= time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getctime(path)))
38         mtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getmtime(path)))
39         # atime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getatime(path)))
40 
41         print(os.path.basename(path), 'createTime:%s' % ctime, 'modifyTime:%s' % mtime)
42 
43 
44 if __name__=='__main__':
45     try:
46         dir_path(path)
47     except Exception as e:
48         print(e)
49 print('总共文件数为{}个'.format(count))
50 print('耗时{}s'.format(time.clock()-start_time))