python - 如何使用循环检查输入是否已存在于 Python 文件中并追加(如果是新的)?

标签 python python-3.x loops append

我想使用循环来检查输入是否已存在于文件中,无论它是否在列表/字典中。虽然我设法将输入记录在 .txt 文件中,但如何检查重复性以便只 append 新输入?

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 文件只是不断记录输入,而不管重复性。

最佳答案

首先,我强烈建议使用 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')



关于python - 如何使用循环检查输入是否已存在于 Python 文件中并追加(如果是新的)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57524496/

相关文章:

python-3.x - 无法将 Blob 存储文件复制/下载到 Azure Functions 文件夹

python - 如何提取特定标题后的 HTML 表格?

php - 名称第一个字母的样式组 PHP 结果

python - keras - 使用 lambda 层时如何避免尺寸错误

python - 二叉树不显示当前 Python 的节点

python - 如何按名称导入自定义python包

Python 和 wx.Image : How to apply a simple function to every pixel FAST?

c - 为什么这是一个无限循环?

python - 如何使用pandas基于两个分类列的组合进行单热编码?

python - 从包含列表的元组列表中进行字典理解