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

Python读取文件时数字丢失零,如何修复该问题?

问题原因

你误用了readline()方法的参数——readline(n)里的n是读取的最大字节数,不是读取第n行。你的代码每次只读取指定长度的字符,导致原本完整的数字被拆分,出现了丢零和异常输出。

修复方案

有两种简单的修复方式:

方式一:一次性读取所有行并处理

读取文件所有行,过滤空行后转成整数,再依次赋值:

with open('stats.txt') as f:
    lines = [int(line.strip()) for line in f if line.strip()]
    money, quantity, min_earnings, max_earnings, min_current_cost, max_current_cost = lines

print(money, quantity, min_earnings, max_earnings, min_current_cost, max_current_cost)

方式二:逐行读取整行内容

调用不带参数的readline(),它会读取完整的一行,再去掉换行符并转成整数:

with open('stats.txt') as f:
    money = int(f.readline().strip())
    quantity = int(f.readline().strip())
    min_earnings = int(f.readline().strip())
    max_earnings = int(f.readline().strip())
    min_current_cost = int(f.readline().strip())
    max_current_cost = int(f.readline().strip())

print(money, quantity, min_earnings, max_earnings, min_current_cost, max_current_cost)

两种方式都能正确输出:2000 0 1100 1400 75 100

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 18:42:15