看板 Python 關於我們 聯絡資訊
各位前輩好,新手發問: 最近在寫登入註冊的backend邏輯 有一個method是: 判斷帳號名稱是否已存在,若不存在則寫入使用者輸入的帳密等資訊 我有一個已經事先預設一些資料的data user.csv 原本預設是這個檔案有東西,所以code如下: with open('user.csv', "r") as f: lines = f.readlines() accounts = [l.split(";;;") for l in lines] usernames = [accounts[x][1] for x in range(0, len(accounts))] if username not in usernames: self.username = username self.password = encrypt_password(password) with open(‘user.csv’ ,'a') as file: file.write(f"\n{self.username};;;{self.password}") result = True else: result=False return result 但是我發現如果我清空這個預設好的檔案,這就無法做了 可能是lines那邊沒有東西的問題 所以多寫一個判斷式在上面那個if外面 if len(lines)==0: self.username=username self.password=self.encrypt_password(password) with open('user.csv','w' as file: file.write(f"{self.username};;;{self.password}\n") result = True 接著寫入上面 else: if username not in usernames: ...... 結果發現使用者輸入後被寫入檔案,然後再被判斷len(lines)!=0 導致帳號已存在無法註冊 result=False 請問該如何解決 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.232.137.113 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1641364909.A.4A7.html ※ 編輯: ajjj840569 (36.232.137.113 臺灣), 01/05/2022 14:45:09
lycantrope: 你可以先用os.path.exists()來判斷要不要create新檔案01/05 15:34
lycantrope: 接著才append你想要的username01/05 15:34
lycantrope: https://reurl.cc/k708Nn01/05 16:02
謝謝 已解決 ※ 編輯: ajjj840569 (36.232.137.113 臺灣), 01/06/2022 13:45:03
leolarrel: 請問是公司派給你的任務嗎?01/07 12:53
不是,只是我的作業中的一個method而已 ※ 編輯: ajjj840569 (36.232.137.113 臺灣), 01/07/2022 14:08:04
leolarrel: 了解,謝謝 01/07 18:36