首页 > 解决方案 > 给定已保存的文件名列表,如何生成固定长度的唯一字符串?

问题描述

如何生成一个新的固定长度的唯一字符串(已经使用相同的方法生成)python中保存的字符串列表?

请参阅下面的代码。我需要多次运行它(可能与完整的可能字符串集的大小一样大(比如长度为 8 个字符))。

strs= load_strings()
#strs= ['sasasafs', 'fdgfdgsa', '43f43y4f', ...]

new_str = generate_new_unique_string(strs) #how to implement this function?
strs.append(new_str)
save_strings(strs)

标签: pythonunique

解决方案


使用 os 检查文件名是否存在加上使用 random 从随机名称生成一些随机文本

检查文件是否存在

import os.path
from os import path

path.exists("guru99.txt")

随机名称(例如长度为 7 个字符)

import random

name = ""
for i in range(7):
    name += chr(random.randint(48,90))

print(name)

推荐阅读