Reputation: 133
I would like to use a loop to check if the input already existed in the file regardless if it is in the list/dict. While I managed to get the input recorded in the .txt file, how do I check for repetitiveness so that I only append a new input?
f = open('History.txt', 'a+')
while True:
new_word = (input('Please enter an English word:'))
if new_word.isalpha() == True:
break
else:
print ('You''ve entered an invalid response, please try again.')
continue
f.seek(0)
f.read()
if new_word in f:
print ('The word has been recorded previously. You may proceed to the next step.')
else:
f.write(new_word + '\n')
f.close()
Currently the .txt file just keep recording the input regardless of repetitiveness.
Upvotes: 2
Views: 347
Reputation: 1236
First I would highly reccomend to use a Contextmanager for opening the file. This will ensure, that the file is closed.
with open(path, "a+") as f:
content = f.read
# DO more stuff
Then in your Code you check if new_word
is in f
. But f
actually is a file object and not a str
. Instead do:
if new_word in f.read():
f.read()
Returns a string
with open('History.txt', 'a+') as f:
while True:
new_word = (input('Please enter an English word:'))
if new_word == "SOME KEYWORD FOR BREAKING":
break
else:
file_position = f.tell() # To Keep appending
f.seek(0) # read from start
file_content = f.read()
f.seek(file_position) # write to end
if new_word in file_content:
print ('The word has been recorded previously. You may proceed to the next step.')
else:
f.write(new_word + '\n')
Upvotes: 1