统计代码行数

该Python代码使用os库遍历指定文件夹,对.py文件进行读取。首先,它使用chardet库检测文件的编码,然后以二进制模式打开文件,读取内容并计算含有 的新行数量,从而统计文件的行数。如果文件为空,则返回0。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 import os
import chardet
# def detect(filename):
#
#     content = open(filename,mode='rb')  # str类型
#     source_encoding = chardet.detect(content.read())['encoding']
#     if source_encoding == 'utf-8':
#         return True
#     else:
#         return False

def linecounter(filename):
    print(filename)
    # filename ='D:\desktopfile\RL code&paper\COP_RL_CL\POMO-master\POMO-master\NEW_py_ver\CVRP\POMO\CVRPEnv.py'
    # file = open(file,'r')
    if os.path.getsize(filename)==0:
        return 0
    content = open(filename, mode='rb')  # str类型\
    r = content.read()
    r.decode(chardet.detect(r)['encoding'])
    # print(r)
    count = r.decode().count('\n')
    content.close()
    return count
    #
    # encode_method = 'utf-8'
    # if chardet.detect(content.read())['encoding'] != 'utf-8':
    #    encode_method = 'ansi'
    # content.close()
    # if source_encoding == 'utf-8':
    #     with open(filename,'r',encoding='utf-8')as file:
    #         count = 0
    #         for line in file:
    #             # assert print(filename)
    #             count += 1
    #         # 一定要关闭文件
    #         file.close()
    # else:

folderpath = os.getcwd()
# 打开一个文件,read权限
count = 0
for root, dirs, files in os.walk(folderpath):
    if root!=folderpath:
        # print("now counting: "+root)  # 当前目录路径
        for file in files:
            if file[-3:] == '.py':
                nowcount = (linecounter(root+"\\"+file))
                print(file+" linecount: "+ str(nowcount))
                count = count+ nowcount
print(count)

将代码放置在项目外运行即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值