2017-02-16 27 views
1

基本上我想嘗試建立一個系統,當你輸入你的ID號碼,再次用相同的號碼重新輸入時,它應該顯示一個錯誤。我試圖在網上尋找一些解決方案,但似乎找不到實際可行的解決方案。這是我到目前爲止所做的代碼:如何在文件中找到重複項

import sys 
N = 0 
while N < 2: 
    ID = input("Please input ID code ") 
    if (len(ID)) == 6: 
     with open('ID1.txt', 'a') as file: 
      file.write(ID + ' ') 
      file.write('\n') 
     N += 1 
     print("ID length: Valid") 
    else: 
     print("ID Code: Error") 
     sys.exit() 

有沒有人有任何想法如何做到這一點?

+1

你必須存儲已經使用的ID。例如在一個列表中。然後檢查它是否已經在列表中。 – pawelty

+0

當第二次輸入的id等於第一次輸入的id,或者輸入的id已經包含在文件中時,你想拋出一個錯誤嗎? – Lex

+0

您可以使用一組來存儲這些ID。對於少量的ID,訪問時間沒有明顯的差異,但是說你有幾百萬個ID。該集會更快 –

回答

0

最簡單的方式,與您的代碼,是加載文本文件,通過拆分把它分解成它的ID被換行,然後看到ID是否在這個新的列表:

N = 1 
while N <= 2: 
    input_id = input('Type your ID: ') 

    assert input_id == 6, 'Invalid ID length' 

    with open('IDs.txt', 'r+') as ids: 
     id_list = ids.read().split('\n') 
     if input_id in id_list: 
      print('This ID already exists') 
      N += 1 
      continue 
     else: 
      ids.write('\n'+input_id) 
      print('valid ID') 
      break 

但清潔方法是使用JSON文件來做到這一點。這樣,您就可以直接加載列表,並會出現格式錯誤的機會也比較少

import json 

N = 1 
while N <= 2: 
    file = open('IDs.json', 'r') 
    ids = json.load(file) 
    file.close() 

    input_id= input('enter your ID:') 
    assert input_id == 6, 'Invalid ID length' 

    if int(input_id) in ids: 
     print('This ID already exists') 
     N += 1 
     continue 
    else: 
     ids.append(int(input_id)) 
     json.dumps('IDs.json', ids) 
     print('ID accepted') 
     break 
0

下面的代碼驗證是否如不存在於文件中的ID,進入2周唯一ID的入檔

N = 0 
while N < 2: 
    ID = raw_input("Please input ID code ") 
    if (len(ID)) == 6: 
     with open('ID1.txt', 'a+') as f: 
      if not any(ID == x.rstrip('\r\n') for x in f): 
       f.write(ID + '\n') 
       N += 1 
相關問題