[英]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.