如何解决While循环生成随机数的替代方法
每次程序运行时,我都会生成一个随机数并使用唯一且随机数创建一个文件名。 有人可以帮助我替代以下代码中的while循环吗?
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()
感谢:)
解决方法
在这种情况下,我认为递归是更合适的解决方案。在此版本中,代码更像是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')
我还认为您需要注意检查文件夹是否存在,并限制尝试创建文件的次数,否则,脚本可能会无限次递归。