python语言程序设计—练习7:文件和数据格式化—文件行数

文件行数

要求:打印输出附件文件的有效行数,注意:空行不计算为有效行数。

分析:读取每一行作为一个元素,放入新列表中;去除空行,即仅有“/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))
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值