最近工作不是很忙,在学习《python核心编程3》,给自己定了一个小目标,每天编码1000行,由于我一边看书,一边敲例子,都是在demo目录下面进行的,
所以写了个监听demo目录的脚本,用来统计每天的编码行数,实现思路就是,遍历demo下的所有文件,找到今日创建的文件,将编码行数累加,下面是代码,
欢迎指正!
# -*- coding: utf-8 -*- """ author:ruiql date:2017/9/4 version:1.0 指定一个目录,针对当日的编码情况,做行数统计 """ import os, sys import time from datetime import datetime EXPECT_ROWS = 1000 #预期完成行数 SCAN_DIR = '/Users/tuyoo/pythondemo/demo' #扫描路径 def statisics_rows(file_list): row_count = 0 for file in file_list: print '#',file.name row_count += len(file.readlines()) file.close() print '今日完成编码行数:%s, 目标行数:%s, 完成度:%0.2f%%' % (row_count, EXPECT_ROWS, row_count*1.0/EXPECT_ROWS*100) def scan_dir_list_today_create(scan_dir): ''' 扫描目录,得到今日创建的文件列表 :param scan_dir: :return: ''' result = [] if not os.path.isdir(scan_dir): raise Exception _recur_dir_get_file(scan_dir, result) return result def _recur_dir_get_file(sub_dir, result): for parent, dirnames, filenames in os.walk(sub_dir): for file in filenames: print parent+'/'+file file = _is_today_create(parent+'/'+file) if file: result.append(file) def _is_today_create(file): create_time = os.path.getctime(file) f_create_time = datetime.fromtimestamp(create_time) now = datetime.now() if (now - f_create_time).days == 0: return open(file) return False statisics_rows(scan_dir_list_today_create(SCAN_DIR))