将光标移到文件开头?

2024-10-04 05:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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

Tags: 文件程序txtlineseek单词wordawesome
2条回答

缩进错误-现在它在第一行中找到不同的文本并自动添加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()

您需要在append模式下打开文件,方法是将“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()

希望这有帮助!你知道吗

相关问题 更多 >