繁体   English   中英

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

[英]Python: check if a variable exists in a .txt file

我的文件夹中有 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

您可以修改您的代码,一次又一次地检查文件将是矫枉过正的,阅读也很费时间。

因此,您可以读取数字文件并过滤 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

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

#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 提供的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM