- def count_code(file_path): # 单文件代码统计
- count=0
- tag=False
- with open(file_path, 'r', encoding='utf-8') as f:
- for line in f:
- if tag and line.startswith('"""') or line.startswith("'''"):
- tag=False
- if tag and not line.startswith('"""') or line.startswith("'''"):
- continue
- if line.startswith("#"):
- continue
- if line.startswith('\n'):
- continue
- count+=1
- return count
- # 所有代码统计量
- def count_file_code(top_packge):
- count_sum = 0
- # 针对文件做处理
- if os.path.isfile(top_packge):
- count=count_code(top_packge)
- return count
- # 针对文件夹做处理
- res = os.walk(top_packge) # 只针对文件夹
- for dir, _, files in res:
- # print(files)
- for file in files:
- file_path = os.path.join(dir, file)
- # print(file_path)
- if file_path.endswith('.py'):
- # print(file_path)
- count=count_code(file_path) # 单文件代码统计
- count_sum += count
- return count_sum
- top=r'G:\Python 代码日常 \ 第一阶段 \ 1 阶段 \ 模块 \ md.py'
- count_sum=count_file_code(top)
- print(f'{top} 文件夹统计代码量为:{count_sum}')
来源: http://www.bubuko.com/infodetail-3227130.html