我想在myWords.txt
文件中保存唯一的单词。我正在搜索一个单词,如果在文件中找到,它就不写它,但是如果找不到,它就写那个单词。问题是,当我第二次运行程序时,指针在文件的末尾,从文件的末尾搜索并再次写入上次写入的单词。我试着在某些位置使用seek(0)
,但不起作用。我做错什么了吗?你知道吗
with open("myWords.txt", "r+") as a:
# a.seek(0)
word = "naughty"
for line in a:
if word == line.replace("\n", "").rstrip():
break
else:
a.write(word + "\n")
print("writing " +word)
a.seek(0)
break
a.close()
我的文字.txt
awesome
shiny
awesome
clumsy
shiny
两次运行代码
我的文字.txt
awesome
shiny
awesome
clumsy
shiny
naughty
naughty
缩进错误-现在它在第一行中找到不同的文本并自动添加
naughty
,因为它不检查其他行。你知道吗你必须使用
for/else/break
结构。else
与for
具有相同的缩进。你知道吗如果程序找到
naughty
,则使用break
离开for
循环,else
将被跳过。如果for
没有找到naughty
,则它不使用break
,然后else
将被执行。你知道吗它的工作原理与
您需要在append模式下打开文件,方法是将“a”或“ab”设置为模式。请参见open()。你知道吗
当您以“a”模式打开时,写入位置将始终位于文件的末尾(追加)。您可以使用“a+”打开以允许读取、向后搜索和读取(但所有写入操作仍将位于文件末尾!)。你知道吗
告诉我这是否有效:
希望这有帮助!你知道吗
相关问题 更多 >
编程相关推荐