Python:检查.txt文件中是否存在变量

时间:2020-09-02 10:07:24

标签: python python-3.x python-requests

我的文件夹中有3个文件。 (pythonapp.py,numbers.txt,usednumbers.txt)。 因此,基本上我的应用程序从(numbers.txt)抓取一个随机字符串,并将其保存到变量中。然后,它将变量写入(usednumbers.txt)。但问题是我不想将任何重复的字符串写入(usednumbers.txt)。因此,我希望我的应用程序在从(numbers.txt)抓取到新的随机字符串时进行检查,以确保它是否已在过去使用(因此如果它存在于usednumbers.txt中)

#imports-------------------------------
import random

#variables-----------------------------
line = random.choice(open('numbers.txt').readlines()) #get a random string
textfile = open("usednumbers.txt", "a") #open usednumbers txt file

#main----------------------------------
#here: need to check if our selected random variable "line"
#is in txt file "usednumbers.txt", if it exists there, we get a new random number
#if it doesn't exist there, we continue and write the variable there (below)

textfile.write(line) #store the number we are going to use
textfile.close() #so in future we avoid using this number again

2 个答案:

答案 0 :(得分:1)

您可以修改代码,而无需一再检查进入文件中,这将是多余的,并且读取非常耗时。

因此,您可以读取数字文件并筛选出usednumber中不存在的数字,并从中选择一个随机数。

#imports-------------------------------
import random

#variables-----------------------------
numbers = open('numbers.txt').read().splitlines() #get a random string

# alreday in usednumbes 
already_in_file = set([x for x in open("usednumbers.txt", "r").read().splitlines()])

# filtering only those number swhich are not in number.txt
numbers = [x for x in numbers if x not in already_in_file]

#choose random number
if len(numbers) >0 :  
  line = random.choice(numbers)

  #main----------------------------------
  textfile = open("usednumbers.txt", "a") #open usednumbers txt file
  textfile.writelines(str(line)+"\n") #store the number we are going to use
  textfile.close() #so in future we avoid using this number again

答案 1 :(得分:0)

您可以检查所选行是否在文本文件的行中。

#imports-------------------------------
import random

#variables-----------------------------
line = random.choice(open('numbers.txt').readlines()) #get a random string
textfile = open("usednumbers.txt", "a") #open usednumbers txt file

#main----------------------------------
#here: need to check if our selected random variable "line"
#is in txt file "usednumbers.txt", if it exists there, we get a new random number
#if it doesn't exist there, we continue and write the variable there (below)
while(line in open('usednumbers.txt').readlines()):
    line = random.choice(open('numbers.txt').readlines()) #get a random string

textfile.write(line) #store the number we are going to use
textfile.close() #so in future we avoid using this number again

更新:

不是最省时的解决方案。

请参阅@Suryaveer Singh提供的解决方案,以获取更优化的解决方案。