How I automate my python script or get multiple entries in one run?

I am running the following python script:

import random

result_str = ''.join((random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()') for i in range(8)))
with open('file_output.txt','a') as out:
    out.write(f'{result_str}\n')

Is there a way I could automate this script to run automatically? or If I can get multiple outputs instantly?
Ex. Right now the output stores itself in the file one by one
kmfd5s6s

But if somehow I can get 1,000,000 entries in the file on one click and there is no duplication.

>Solution :

You need to nest your out.write() in a loop, something like this, to make it happen multiple times:

import random

with open('file_output.txt','a') as out:
    for x in range(1000): # the number of lines you want in the output file
        result_str = ''.join((random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()') for i in range(8)))
        out.write(f'{result_str}\n')

However, while unlikely, it is possible that you could end up with duplicate rows. To avoid this, you can generate and store your random strings in a loop and check for duplicates as you go. Once you have enough, write them all to the file outside the loop:

import random

results = []
while len(results) < 1000: # the number of lines you want in the output file
    result_str = ''.join((random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()') for i in range(8)))
    if result_str not in results: # check if the generated result_str is a duplicate
        results.append(result_str)

with open('file_output.txt','a') as out:
    out.write( '\n'.join(results) )

Leave a Reply