2016-11-12 75 views
0

我想在我的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 
+0

是没有意义的break'后'把任何东西。你必须把它放在'break'之前 – furas

+0

@furas谢谢。编辑。我也尝试过,但不起作用.. – Amar

+0

我认为你有错误的缩进。你需要'for/else'构造,而不是'if/else' - 所以'else'必须在下面'' – furas

回答

0

你有错误的缩进 - 现在它在第一行发现不同的文本,并自动添加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() 
+0

谢谢你。我的坏..它的作品。 – Amar

0

您需要追加模式打开的文件,通过设置“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() 

希望这有助于!