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

Python循环统计文件行数写入文件结果为0的问题排查

问题:统计三元组排列数时循环内计数始终为0

原脚本试图生成满足i<j<k的三元组并统计每组k对应的数量,但执行后输出文件中计数全为0:

tmp = open("tmp_out.txt","w+")
out = open("output_trip.txt", "w")
N = 4
for k in range(2,N+1):
    count = 1
    for j in range(1,k):
        for i in range(0,j):
            tmp.write("({},{},{})\n".format(i,j,k))
            count = len(tmp.readlines())
    out.write('{}{:10d}\n'.format(k,count))

期望输出:

2      1
3      4
4      10

实际输出:

2      0
3      0
4      0

解决方案

错误原因

  1. 文件写入后,文件指针停在末尾,此时调用readlines()会从末尾开始读取,自然返回空列表,长度为0。
  2. 即使移动指针,频繁读写文件也会降低效率,完全没必要通过文件来统计数量。

修改后的代码(推荐方案:直接变量计数)

不需要借助临时文件统计,直接用count变量累加即可,同时保留三元组写入逻辑:

tmp = open("tmp_out.txt","w+")
out = open("output_trip.txt", "w")
N = 4
for k in range(2,N+1):
    count = 0  # 初始化为0,每次k循环重置
    for j in range(1,k):
        for i in range(0,j):
            tmp.write("({},{},{})\n".format(i,j,k))
            count += 1  # 每写入一个三元组,计数加1
    out.write('{}{:10d}\n'.format(k,count))

# 手动关闭文件
tmp.close()
out.close()

进阶优化:使用with语句自动管理文件

避免手动关闭文件的疏漏,推荐用with上下文管理器自动处理文件生命周期:

N = 4
with open("tmp_out.txt","w+") as tmp, open("output_trip.txt", "w") as out:
    for k in range(2,N+1):
        count = 0
        for j in range(1,k):
            for i in range(0,j):
                tmp.write("({},{},{})\n".format(i,j,k))
                count += 1
        out.write('{}{:10d}\n'.format(k,count))

如果一定要通过文件统计(不推荐)

如果坚持要读取文件统计,需要每次写入后刷新缓冲区,并调整文件指针位置:

tmp = open("tmp_out.txt","w+")
out = open("output_trip.txt", "w")
N = 4
for k in range(2,N+1):
    count = 0
    for j in range(1,k):
        for i in range(0,j):
            tmp.write("({},{},{})\n".format(i,j,k))
            tmp.flush()  # 刷新缓冲区,确保写入内容落盘
            tmp.seek(0)  # 将文件指针移回开头
            count = len(tmp.readlines())
            tmp.seek(0, 2)  # 写之前把指针移回末尾,避免覆盖内容
    out.write('{}{:10d}\n'.format(k,count))

tmp.close()
out.close()

但这种方法效率极低,远不如直接用变量计数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 00:25:03