前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >统计python代码行数

统计python代码行数

作者头像
py3study
发布2020-01-13 15:33:48
1.9K0
发布2020-01-13 15:33:48
举报
文章被收录于专栏:python3python3python3

    addhosts项目已接近尾声,我很想知道我们写了多少行代码。

一、需求

    统计源码目录下py文件的代码行数。

16a2284fa7175bc6f107b02959024ff6.png
16a2284fa7175bc6f107b02959024ff6.png

二、脚本分析

    获取指定目录下所有的.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()

运行结果如下:

cc2ac41637ba3f31728df8ad7e07162a.png
cc2ac41637ba3f31728df8ad7e07162a.png

四、总结

问题:

    在执行open(file).readlines()时,遇到了如下错误

“UnicodeDecodeError: 'gbk' codec can't decode byte 0xaf in position 548: illegal multibyte sequence”

解决方法:

    在open时,设置encoding='utf-8'后,问题得到解决。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档