【问题标题】:Python not looping the specified amount of timesPython没有循环指定的次数
【发布时间】:2020-08-01 04:09:01
【问题描述】:

在 python 文件中,我试图将数组写入 txt 文件。 这个数组目前是 87822 长(但它不是固定的,取决于输入),数组中的每个位置都是 3 个字母的文本(例如"gtg")。 我正在使用下面的循环将所有这些写入 output.txt,但它只打印数组中大约 87449 个项目。

for i in range(0, len(splitArray)):
        output.write(splitArray[i])

print(len(splitArray)) 运行时,返回87822

我尝试用更简单的循环替换这些数字,如下所示。

for t in range(0, 87822, 1):
    output.write(str(t))

这一次又只达到了87449的数量,即使87822的最大值增加到90000,还是差了912

这可能是什么原因造成的? for 循环是否有上限,以便它们在无限循环之前中断?感谢您的帮助。

【问题讨论】:

  • 不可重现
  • 文件是否在循环后被关闭?对文件的写入可能会被缓冲
  • 不,python 中的 for 循环没有上限。该文件可能被缓冲
  • 试试:output.flush() 或类似的东西
  • 它不能解决问题,但我建议你养成使用for item in splitArray: 而不是for i in range(len(splitArray)): 的习惯。它更pythonic,使代码更容易理解。

标签: python for-loop


【解决方案1】:

为什么不用这个循环?这样更好。

for item in splitArray:
    output.write(item)

另外,你在with 块中使用输出吗? with open(out_filename, 'w') as out_file: 是一种更安全的文件管理方式,因为它会在执行with 后自动关闭它们

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多