统计python代码行数
2017-11-15 21:08
447 查看
addhosts项目已接近尾声,我很想知道我们写了多少行代码。
一、需求
统计源码目录下py文件的代码行数。
二、脚本分析
获取指定目录下所有的.py文件,对文件进行遍历;
读取每个文件,对文件内容进行遍历,过滤掉空行和注释;
三、实现及结果
四、总结
问题:
在执行open(file).readlines()时,遇到了如下错误
“UnicodeDecodeError: 'gbk' codec can't decode byte 0xaf in position 548: illegal multibyte sequence”
解决方法:
在open时,设置encoding='utf-8'后,问题得到解决。
一、需求
统计源码目录下py文件的代码行数。
二、脚本分析
获取指定目录下所有的.py文件,对文件进行遍历;
读取每个文件,对文件内容进行遍历,过滤掉空行和注释;
三、实现及结果
#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()运行结果如下:
四、总结
问题:
在执行open(file).readlines()时,遇到了如下错误
“UnicodeDecodeError: 'gbk' codec can't decode byte 0xaf in position 548: illegal multibyte sequence”
解决方法:
在open时,设置encoding='utf-8'后,问题得到解决。
相关文章推荐
- 用python代码统计大文本文件行数
- 代码行数统计的Java和Python实现
- [python]写一个统计代码行数的codeCounter 推荐
- 统计代码行数(python实现)
- Python 统计代码的行数,Python脚本 统计代码
- python 代码统计文件的行数
- (python) 统计代码行数
- python统计指定目录内文件的代码行数
- 代码行数统计(python实现)
- 【Python】代码行数统计
- Python脚本实现代码行数统计代码分享
- python实现统计代码行数的方法
- 代码行数统计(python实现)
- 统计代码行数的python小工具
- python实现代码行数统计示例分享
- Python统计python文件中代码,注释及空白对应的行数示例【测试可用】
- python实现统计代码行数的方法
- 统计项目的代码行数(python处女作)
- 第0007道练习题_Python统计代码行数注释行数空白行数
- python实现代码行数统计