-1

I want the code to write 100 random files from 1 to 9999999999 in a file called users.txt but it always only writes two lines, one of them a random number, one of them blank. Code:

import random
wrote = 0
while True:
    if wrote == 100:
        print("writing finished!")
        break
    else:
        with open('users.txt', 'w') as f:
            f.write(str(random.randint(1, 9999999999)) + '\n')
        wrote = wrote + 1

some random result I get: 3218450110 what is wrong?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 4
    You open the file over and over again and overwrite the content in each iteration, open the file just once, outside of the loop. – luk2302 Nov 02 '21 at 09:41
  • 1
    Note that opening the file in write (`'w'`) mode truncates (erases) it before writing. Either open it once, or open it in append mode ('a'). – Thierry Lathuille Nov 02 '21 at 09:44

1 Answers1

1

Opening a file in w (write) mode clears the previous contents of the file. Therefore, the contents of the file are cleared after every loop and only the last iteration of the loop is saved.

To fix this. open it once outside of the loop:

import random
wrote = 0
f = open('users.txt', 'w')
while True:
    if wrote == 100:
        print("writing finished!")
        break
    else:
        f.write(str(random.randint(1, 9999999999)) + '\n')
        wrote = wrote + 1
f.close()

Result: 100 lines.