gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:24:30 24 4
gpt4 key购买 nike

我想使用循环来检查输入是否已存在于文件中,无论它是否在列表/字典中。虽然我设法将输入记录在 .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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com