addhosts项目已接近尾声,我很想知道咱们写了多少行代码。
python
1、需求ide
统计源码目录下py文件的代码行数。
code
2、脚本分析blog
获取指定目录下全部的.py文件,对文件进行遍历;utf-8
读取每一个文件,对文件内容进行遍历,过滤掉空行和注释;
get
3、实现及结果源码
#coding:utf-8 import os class StatLines(object): def __init__(self,path): self.path = path def stat_lines(self): file_list = os.listdir(self.path) os.chdir(self.path) total = 0 for file in file_list: if file.endswith('.py'): lines = open(file, encoding='utf-8').readlines() count = 0 for line in lines: if line == '\n': continue elif line.startswith('#'): continue else: count += 1 total += count print('%s has %d lines' %(file,count)) print('total lines is: %d' %total) if __name__ == '__main__': sl = StatLines('E:\\Python_Project\\addhost_v2\\addhosts') sl.stat_lines()
运行结果以下:it
4、总结io
问题:
class
在执行open(file).readlines()时,遇到了以下错误
“UnicodeDecodeError: 'gbk' codec can't decode byte 0xaf in position 548: illegal multibyte sequence”
解决方法:
在open时,设置encoding='utf-8'后,问题获得解决。