You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python任务管理器项目:读取两个文本文件总行数的代码求助

修正Python读取文件总行数的代码

原代码存在两个问题:

  • 语法错误:for line in admin_file: 后的代码没有缩进,不符合Python的缩进规则
  • 逻辑错误:遍历文件行后,文件指针已移动到文件末尾,此时调用readlines()会返回空列表,导致统计的行数为0

修正方案1:直接读取所有行统计(适合小文件)

with open('user.txt','r') as admin_file:
    total = len(admin_file.readlines())
    print("Total number of users:", total)

with open('tasks.txt','r') as admin_file:
    total = len(admin_file.readlines())
    print("Total number of tasks:", total)

修正方案2:逐行计数(适合大文件,内存占用更低)

def count_lines(file_path):
    count = 0
    with open(file_path, 'r') as f:
        for _ in f:
            count += 1
    return count

print("Total number of users:", count_lines('user.txt'))
print("Total number of tasks:", count_lines('tasks.txt'))

第一种方案一次性将文件内容读入内存,适合小文件;第二种方案逐行遍历计数,不会占用过多内存,更适合大文件场景。

内容的提问来源于stack exchange,提问作者Rdpcop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 12:39:26