统计python代码行数

发布时间:2020-06-07 17:04:04 作者:ilanqing
来源:网络 阅读:4941

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

一、需求

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

    统计python代码行数


二、脚本分析

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

运行结果如下:

统计python代码行数


四、总结

    问题:

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

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

    解决方法:

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

推荐阅读:
  1. php如何统计文件的代码行数
  2. PHP统计代码行数的小代码

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 代码行数

上一篇:mysql数据库环境优化

下一篇:2019北美KubeCon+CloudNativeCon上的K8S五大趋势

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》