我正在尝试使用 For 循环在 .TXT 文件中写入数字 1 - 4096,但是当循环完成时,.TXT 文件中只有数字 4096

I am trying to write numbers 1 - 4096 in a .TXT file using a For Loop, but when the loop is finished, there is only the number 4096 in the .TXT file

我有 2 个文件:

text.txt

并且:

main.py

main.py中,我有以下代码:

for i in range(1,4097):
    i = str(i)
    file = open("text.txt","w")
    file.write(i)

如您所见,我想生成 1 - 4096 之间的所有数字,但是当我 运行 脚本时,它只在 text.txt 中写入 4096

如何在 text.txt 中写入数字 1 - 4096?

(顺便说一下,我把 i 设为字符串 (str()) 因为我不能在文本文件中写 int() (i)。

谢谢

丹尼尔

您应该在进入 for 循环之前进行 open 调用。否则每次都会覆盖文件。

您想在整个循环中打开文件描述符:

with open('text.txt', 'w') as op:
   for i in range(0,10):
       op.write(f'{i}\n')

还可以使用 f 字符串避免将 i 强制转换为字符串。

这是file=open(‘test.txt’,‘w+’)中的‘w+’引起的。 如果将“w+”替换为“a+”,它应该可以工作。 这是因为 w+ 覆盖了文件,所以数字被写入,但立即被下一个数字替换,导致只剩下最后一个数字。 a+ 附加到文件中,因此您将在 test.txt 中获得从 1 到 4096 的所有数字。 作为旁注,您忘记关闭文件,这可能会导致以后出现问题。 这是您最好编写代码的方式:

for i in range(1,4097):
    with open("text.txt", "a+") as file:
        file.write(f"\n{i}")

这样更好,因为它会在 with 块中的任何内容为 运行 后自动关闭文件。您也可以在末尾写 file.close() 而不是这样做,但这需要多一行代码。 f'\n{i} 确保在打印下一个数字之前有一个新行。

我解决这个问题的方法是这样做:

file = open("text.txt","a")
for i in range(1,4097):
    i = str(i)
    file.write(str(i) + "\n")

file.close()

而不是这个:

for i in range(1,4097):
    i = str(i)
    file = open("text.txt","w")
    file.write(i)

如您所见,它不起作用的原因是当 open("text.txt","w") 运行 时,它每次都会覆盖 text.txt 因为 open("text.txt") 被设置为 write 模式 (w) 而不是 append 模式 (a)。所以每次 运行,它都会覆盖每个数字。另外,如果我想每次 运行 都换行,我需要做的就是将 file.write(str(i)) 替换为:file.write(str(i) + "\n").