0

I am trying to generate a unique number every time the script is triggered. But, in my script I am giving a range say 1-10, which I am using later to create a unique file name every time. So after generating all random number within range of 1 to 10, the script throws an infinite loop.

import random
import os
import sys

class Random_no:
    def generate_random_number(self):
        random_number = random.randint(1, 10)
        return str(random_number[0])
    
    def execute(self):
        test_flag=False
        save_path = 'C:\\Users\\Krishma\\Desktop\\mt_config_test'
        while not test_flag:
            mt_config_file_name = "mt_config" + "_" + self.generate_random_number() + ".json"
            print(f"mt config file name is :{mt_config_file_name}")
            if os.path.exists(save_path + "\\" + mt_config_file_name):
                print(f"FILE ALREADY EXITS:{mt_config_file_name}")
            else:
                test_flag=True
        mt_config_path = os.path.join(save_path, mt_config_file_name)
        with open(mt_config_path, 'w+'):
            pass
            
        print(mt_config_path)

obj = Random_no()
obj.execute()

PLEASE HELP ME WITH THIS:)

  • Why do the numbers need to be random, and why do they need to be between one and ten? – Paul M. Nov 06 '20 at 14:01
  • .. so what do you expect to happen when all the random numbers are used up? It seems like you've already (kind-of) solved the "without repetition" part, so it's more about the logic issue about what you want to happen. – MatsLindh Nov 06 '20 at 14:06
  • Does this answer your question? [Python: How to create a unique file name?](https://stackoverflow.com/questions/2961509/python-how-to-create-a-unique-file-name) – Peter O. Nov 06 '20 at 15:22
  • It appears your goal is ultimately to generate the name of a file that doesn't exist yet. In that case, generate the name, then open the file directly without checking if it exists first. If it fails you know the file already exists. – Peter O. Nov 06 '20 at 15:23

0 Answers0