what I am trying to do is add a string only if not available in a text file The problem is I can't read the content of the text file within an if statement
import random
import time
def random_srting(length=1):
digits ='abcdefghijklmnopqrstuvwxyz1234567890._'
return ''.join(random.choice(digits) for i in range(length))
Input = str(input())
with open('4LWordList.txt','a ') as f:
while Input != "s":
time.sleep(1)
word = (random_srting(1) ".abc")
if (word in f.read()): #here is the problem 'word' isn't being checked in 'f' because it's not reading the content of 'f'
print("skip : " word)
elif (word not in f.read()): #same problem here
f.write(word "\n")
print("add : " word)
CodePudding user response:
The problem here is, that the read
function has a pointer to mark how far it read trough the file. If you don't reset the pointer to the beginning, it will continue reading at the end of the file in every subsequent call, which will result in an empty string. So, instead of reading the file contents in each if
statement, read the contents either once and save it to a variable, or reset the pointer before reading using f.seek(0)
.
See also this related question: Re-read an open file Python
Btw theres some other issues with your code: The input
function isn't placed within the while
loop, hence it is only asking for input once, then looping forever or not at all. Also, the condition in the first if
statement can either be True
or False
. Hence, you should replace the elif
by else
instead, as the code only enters this branch, if the condition of the if
evaluates to False
.
CodePudding user response:
Store the file contents in a set, and then you don't need to re-read the file each time you add a word:
import random
def random_string(length):
return ''.join(random.choices(
'abcdefghijklmnopqrstuvwxyz1234567890._',
k=length
))
with open('4LWordList.txt') as f:
words = set(f.readlines())
with open('4LWordList.txt','a') as f:
while input() != "s":
word = random_string(1) ".abc"
if word in words:
print("skip : ", word)
else:
words.add(word)
f.write(word "\n")
print("add : ", word)
When you open a file, you create an iterator that starts at the start of the file, and read()
consumes the iterator, advancing it to the end of the file; to re-read it you need to either seek
back to the beginning or re-open the file. The simpler (and faster) solution for a small file is to just keep the contents in memory.