如何使用循环检查输入的内容是否已存在于Python的文件中,并追加新的内容?

时间:2019-08-16 12:15:42

标签: python python-3.x loops append

我想使用一个循环来检查输入是否已经存在于文件中,而不管它是否在列表/字典中。在设法将输入记录在.txt文件中的同时,如何检查重复性,以便仅添加新的输入?

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

当前.txt文件只保留记录输入内容,而不管其是否重复。

1 个答案:

答案 0 :(得分:1)

首先,我强烈建议使用Contextmanager打开文件。这样可以确保文件已关闭。

with open(path, "a+") as f:
    content = f.read
    # DO more stuff

然后在您的代码中检查new_word是否在f中。但是f实际上是文件对象,而不是str。而是:

if new_word in f.read():

f.read()返回一个字符串

可能的最终代码

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