简体   繁体   中英

How do I use a loop to check if the input already existed in the file in Python and append if it's new?

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.

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

Possible final Code

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')



The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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