pythonstringfor-loopinteger

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


I have 2 files:

text.txt

And:

main.py

In main.py, I have the following code:

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

As you can see, I want to generate all numbers from 1 - 4096, but when I run the script, it only writes 4096 in text.txt.

How can I write numbers 1 - 4096 inside text.txt?

(By the way, I made i a string (str()) because I cannot write an int() (i) in a text file.

Thanks

Daniel


Solution

  • The way I fixed this is by doing this:

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

    Instead of this:

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

    As you can see, the reason it did not work is when open("text.txt","w") ran, it overrighted text.txt everytime because open("text.txt") was set to write mode (w) not append mode (a). So everytime it ran, it overrighted each number. Also, if I wanted to make a newline every time it ran, all I would need to do is replace file.write(str(i)), with this: file.write(str(i) + "\n").