Writing multiple characters into a file, but only see one character? - Python

Viewed 211

I want to write random numbers between one and zero, eighty times. This should write 010100001010100101001010100101010.... whatever (80 times) into a txt file, but instead I get one single number. Why does

from random import random

bro = int(input('Amount: '))

for i in range(bro):
    open('e.txt', 'w').write(str(round(random())))

not work?

2 Answers

Doing open('e.txt', 'w') inside the for loop means that you're recreating the file on every iteration (i.e., clearing whatever contents it may hold).

Hence, when the program completes, the file will hold only the last piece of data written into it.

You should open the file once and then write to the opened file. You can also use randint(0, 1) instead of round(random()):

from random import randint

amnt = 80

with open('e.txt', 'w') as f:
    for i in range(amnt):
        f.write(str(randint(0, 1)))
Related