Random number generator in Python on Linux
Question: This is the code that i've written:

    
    
    import os
    import string
    import random
    def id_generator(size=8, chars=string.digits):
        return ''.join(random.choice(chars) for _ in range(size))
    b="echo " + id_generator() + "> file.txt"
    os.system(100*b)
    

Now the problem is that when i run the script it returns one random number not
100. I want that when i open **file.txt** it must be like:

    
    
    123456
    241721
    126428
    

How can i resolve this problem?


Answer: The redirection overwrites the previous contents of the file. You want `>>`,
not `>`.

There is no need in using the obsolete `os.system()` and redirections here, by
the way. You can do:

    
    
    with open('file.txt', 'w') as f:
        for _ in range(100):
           f.write(id_generator() + '\n')
    

This is also more cross-platform.

