2016-11-12 74 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() 

希望這有助於!