# 自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来
1.1 以读文件的模式打开一个文件对象,使用Python内置的open()
函数,传入文件名和标示符
f = open(‘/Users/michael/test.txt‘, ‘r‘)
with
语句来自动帮我们调用close()
方法with open(‘/path/to/file‘, ‘r‘) as f: print(f.read())
readline()
可以每次读取一行内容,调用readlines()
一次读取所有内容并按行返回list
for line in f.readlines(): print(line.strip()) # 把末尾的‘\n‘删掉
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
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
stip()方法语法:
str.strip([chars]);
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)
原文:https://www.cnblogs.com/kkkhycz/p/11639235.html