007-使用python统计代码行数,空行以及注释

# 自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来

1.打开文件方法

1.1 以读文件的模式打开一个文件对象,使用Python内置的open()函数,传入文件名和标示符

f = open('/Users/michael/test.txt', 'r')

1.2 Python引入了with语句来自动帮我们调用close()方法

with open('/path/to/file', 'r') as f:
    print(f.read())

1.3 调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list

for line in f.readlines():
    print(line.strip()) # 把末尾的'\n'删掉

2.python计算文件行数的三种方法

def linecount_1():
    return len(open('data.sql').readlines())#最直接的方法

def linecount_2():
    count = -1 #让空文件的行号显示0
    for count,line in enumerate(open('data.sql')): pass 
    #enumerate格式化成了元组,count就是行号,因为从0开始要+1
    return count+1

def linecount_3():
    count = 0
    thefile = open('data.sql','rb')
    while 1:
        buffer = thefile.read(65536)
        if not buffer:break
        count += buffer.count('\n')#通过读取换行符计算
    return count

3.Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

stip()方法语法:

str.strip([chars]);

4.startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查

startswith()方法语法:

str.startswith(substr, beg=0,end=len(string))

完整代码:

# conding:utf-8

count = 0 sum = 0 catalog = open(r"D:\Users\sky\PycharmProjects\untitled2\dict.py") t = len(open(r"D:\Users\sky\PycharmProjects\untitled2\dict.py").readlines())  #统计行数 for line in catalog.readlines(): line = line.strip() #去掉每行头尾空白 print(line) if line == "": count += 1 if line.startswith("#"): #startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False sum += 1 print("统计的文件行数为:%d行" %t) print("统计文件的空行数为:%s" %count) print("统计的注释行数为:%s" %sum)

 

posted @ 2019-10-09 07:39  梦幻星  阅读(2070)  评论(0编辑  收藏  举报