检查是否已经存在随机数

时间:2020-04-30 10:01:56

标签: python

我想生成随机数并将其写入.txt文件。 范围是:str(random.randint(0,10))

在生成随机数之前,我的代码应首先检查.txt文件。在此文本文件中,已经记录了一些随机数。如果该随机数已经存在,它将为我生成一个新的随机数并将其添加到我的.txt文件中。

randomTxt = './random.txt'

def checkRandomNumberExists(value):
    with open(randomTxt, 'a+') as random:
        genRandom = str(random.randint(1,10))
        if value in random:
            random.write(genRandom)
        random.write('\n')

我问我走错路了。 谁能帮帮我吗。 预先谢谢你

2 个答案:

答案 0 :(得分:0)

尝试在内部使用while循环:

randomTxt = './random.txt'
with open(randomTxt, 'a+') as file:
    text = file.read()
    genRandom = str(random.randint(1,10))
    while genRandom in text:
        genRandom = str(random.randint(1,10))
    file.write(genRandom)
    file.write('\n')

注意:请不要使用内置名称(即随机名称)来命名文件和变量,因为它可能会覆盖原始模块。

答案 1 :(得分:0)

我看不到在函数中使用参数的任何原因,因为您正在生成随机数,并且正在生成1-10之间的随机数,如果在文本中添加了所有数字,如果它添加了除1以外的数字,该怎么办2,3 ... 10,请修改您的问题并提及。

下面的代码将检查文本文件中是否存在数字,如果文本文件中不存在数字,它将在文本文件中添加该数字,否则它将打印该数字已经退出的消息。

代码

import random
lines = []
num = random.randint(0,10)
f= open("random.txt","w+")
def checkRandomNumberExists():
    with open("random.txt") as file:
        for line in file: 
            line = line.strip()
            lines.append(line)

    if str(num) not in lines:
        with open("random.txt", "a") as myfile:
            myfile.write(str(num)+'\n')
            print(str(num)+ ' is added in text file')
    else:
        print(str(num)+ ' is already exists in text file')

checkRandomNumberExists()  

插入新值时输出

7 is added in text file

文本文件中已经有值时输出

7 is already exists in text file