python实践代码

打开文件,统计注释行数占总行数的比例(注释行都以#开头)

import os.path
from datetime import datetime

f_name = 'C:/Users/lenovo/Desktop/test/a.txt'

cnt = 0
useful_cnt = 0

with open(f_name, 'r') as f:
    lines = f.readlines()
    for line in lines:
        if line[0] != '#':
            useful_cnt = useful_cnt+1
        cnt = cnt+1

print(useful_cnt/cnt)


end

Comments

留言