将光标移动到文件开头?

Bring the cursor to start of file?

我想在我的 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()

myWords.txt

awesome
shiny
awesome
clumsy
shiny

上运行宁码两次

myWords.txt

awesome
shiny
awesome
clumsy
shiny
naughty
naughty

您需要通过设置 "a" 或 "ab" 作为模式以追加模式打开文件。参见 open()。

当您以"a"模式打开时,写入位置将始终在文件末尾(追加)。您可以使用 "a+" 打开以允许读取、向后查找和读取(但所有写入仍将位于文件末尾!)。

告诉我这是否有效:

with open("myWords.txt", "a+") as a:

    words = ["naughty", "hello"];
    for word in words:
        a.seek(0)
        for line in a:
            if word == line.replace("\n", "").rstrip():
                break
            else:
                a.write(word + "\n")
                print("writing " + word)
                break

    a.close()

希望对您有所帮助!

您的缩进错误 - 现在它在第一行找到不同的文本并自动添加 naughty 因为它不检查其他行。

你必须使用for/else/break构造。 elsefor 具有相同的缩进。

如果程序找到 naughty 则它使用 break 离开 for 循环并且 else 将被跳过。如果 for 没有找到 naughty 那么它就不会使用 break 然后 else 将被执行。

with open("myWords.txt", "r+") as a:
    word = "naughty"
    for line in a:
        if word == line.strip():
            print("found")
            break
    else: # no break 
        a.write(word + "\n")
        print("writing:", word)

    a.close()

它的工作原理类似于

with open("myWords.txt", "r+") as a:
    word = "naughty"

    found = False

    for line in a:
        if word == line.strip():
            print("found")
            found = True
            break

    if not found:
        a.write(word + "\n")
        print("writing:", word)

    a.close()