Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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) )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading