文件行数
要求:打印输出附件文件的有效行数,注意:空行不计算为有效行数。
分析:读取每一行作为一个元素,放入新列表中;去除空行,即仅有“/n”的行;输出列表长度。
不能用for循环,去除仅有’/n’的行
refer: https://www.cnblogs.com/aloiswei/p/9083638.html
f = open('latex.log', 'r', encoding = 'utf-8')
t = f.readlines() #read all lines as a list, each line is an element.
'''
for i in t:
if i == "\n":
t.remove(i)
# notice: for loop can't remove all '\n' or ''
#refer:https://www.cnblogs.com/aloiswei/p/9083638.html
'''
while '\n' in t:
t.remove('\n')
print('共{}行'.format(len(t)))
【参考代码】
分析:分行读取,逐行处理;每行移除’\n’,去掉空字符,循环计次
f = open("latex.log")
s = 0
for line in f:
line = line.strip('\n')
if len(line) == 0:
continue
s += 1
print("共{}行".format(s))