2

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?

Alex
  • 34,899
  • 5
  • 77
  • 90
  • It's wasteful to reopen the same file for every write. What you should do `open` it first, run the `for` loop, and then call `close()`. – Daniel Walker Dec 17 '20 at 00:34
  • 2
    `open('e.txt', 'w')` opens `e.txt` for writing and if there is anything in that file, deletes the contents. – zvone Dec 17 '20 at 00:45

2 Answers2

3

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.

goodvibration
  • 5,980
  • 4
  • 28
  • 61
  • 1
    Thank you for _why_ it happened. Still need _how_ to fix it though. :l – Unknown Bobby Dec 17 '20 at 00:31
  • @UnknownBobby: See the other answer; you need to use `a+` instead of `w` AFAIK. – goodvibration Dec 17 '20 at 00:31
  • 2
    Opening the file within the loop is the problem; not the mode. You only need to open the file once before the for loop. –  Dec 17 '20 at 01:08
  • @UnknownBobby: Ah yes, see the comment above. My answer actually **does** give you the full solution. You can `open('e.txt', 'w')` once before the loop, and that's it. No need to change the `'w'` mode. – goodvibration Dec 17 '20 at 07:18
3

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)))
ssp
  • 1,666
  • 11
  • 15