0

I am generating a random number and creating a file name with a unique and random number everytime program runs. Can someone help me with alternative for while loop in the following code.

import random
import os
import sys


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

obj = Random_no()
obj.execute()

THANKS IN ADVANCE :)

  • What's the problem with it? – Barmar Nov 12 '20 at 08:15
  • You should be consistent about using `os.path.join()` rather than doing string concatenation to create pathnames. – Barmar Nov 12 '20 at 08:17
  • Welcome to Stack Overflow! If the code works and you're looking for advice on improving it, [codereview.se] is the appropriate place. But see https://codereview.meta.stackexchange.com/questions/5777/a-guide-to-code-review-for-stack-overflow-users first. – Barmar Nov 12 '20 at 08:17

1 Answers1

2

I think for such cases recursion is more suitable solution. In this version, the code is more pythonic.

import os
import random


class randomNo:

    base_dir = os.path.abspath(os.path.dirname(__file__))

    def get_random_num(self):
        return random.randint(1, 10)

    def create_config(self, path=None):
        if not path:
            path = self.base_dir

        filename = f'{str(self.get_random_num())}.json'
        file_path = os.path.join(path, filename)

        if os.path.exists(file_path):
            print(f'FILE ALREADY EXIST: {file_path}')
            self.create_config(path)
        else:
            with open(file_path, 'w+'):
                print(file_path)


rn = randomNo()
rn.create_config(path=r'C:\Users\myname\Desktop\config_test')

I also think you need to take care of checking the existence of a folder and limiting the number of attempts to create a file, otherwise at one moment the script may go into an infinite recursion.

nosheyakku
  • 316
  • 2
  • 11
  • 2
    I don't think recursion is suitable in this case (in python at least). It unnecessarily inflates the call stack (risking a RecursionError) and since it is not predictable, you'll get a different stack trace for Exceptions raised in the else branch each time you execute it. Also read [this answer](https://stackoverflow.com/a/3323013). – danzel Nov 12 '20 at 09:28
  • @danzel oh that's good to know, thanks for the info. – nosheyakku Nov 12 '20 at 09:31