2016-11-11 100 views
0

我有記錄用戶的Python 3.5代碼。如何將文件鏈接到文檔?

它創建了一個用戶,並記錄他們。

後,我殺程序,然後重新運行它,它不記得它創建的用戶的詳細信息。

如何將文件鏈接到文檔?

+2

請分享一些你已經嘗試過的代碼,如果你表明你已經爲解決問題做了一些工作,那麼你更有可能在這裏獲得幫助。 – cfreear

回答

0

本週早些時候我正在做一個類似的項目,這就是我所要做的!

import csv 

def displayMenu(): 
    status = input("Are you a registered user? y/n? ") 
    if status == "y": 
     login() 
    elif status == "n": 
     newUser() 

def login(): 

    with open('users.txt') as csvfile: 
     reader = csv.DictReader(csvfile) 
     database = [] 
     for row in reader: 
      database.append(dict(username=row['username'], 
           password=row['password'], 
           function=row['function'])) 

loggedin = False 
while not loggedin: 
    Username = input('Fill in your username: ') 
    Password = input('Fill in your password: ') 
    for row in database: 
     Username_File = row['username'] 
     Password_File = row['password'] 
     Function_File = row['function'] 
     if (Username_File == Username and 
      Password_File == Password and 
       Function_File == 'user'): 
      loggedin = True 
      print('Succesfully logged in as ' + Username) 
     elif (Username_File == Username and 
       Password_File == Password and 
       Function_File == 'admin'): 
      loggedin = True 
      print('Succesfully logged in as the admin.') 
     if loggedin is not True: 
      print ('Failed to sign in, wrong username or password.') 

def newUser(): 
    signUp = False 
    while not signUp: 
     NewUsername = input("Create login name: ") 
     NewUsername = str(NewUsername) 
     with open('users.txt', 'r') as UserData: 
       reader = csv.reader(UserData, delimiter=',') 
     if (NewUsername) in open('users.txt').read(): 
      print ('Login name already exist!') 

     else: 
      NewPassword = input("Create password: ") 
      NewPassword = str(NewPassword) 
      with open('users.txt', 'a') as f: 
       writer = csv.writer(f) 
       UserPassFunction = (NewUsername,NewPassword,'user') 
       writer.writerows([UserPassFunction]) 
      print("User created!") 
      signUp = True 






# ---- Main ---- # 

displayMenu() 
0

您可以讀取和寫入數據到一個文件來存儲用戶的登錄細節,其中Logindetails.txt是存儲在相同的位置,你的程序.txt文件。 Windows記事本使用.txt文件。

import linecache 
with open("LoginDetails.txt", "r") as po: 
    LoginDetails = linecache.getline('LoginDetails.txt', int(LineNumber)).strip() 

「r」將以只讀模式打開文件。 「r +」將允許您讀取和寫入文件。

def replace_line(file_name, line_num, text): 
    lines = open(file_name, 'r').readlines() 
    lines[line_num] = text 
    with open(file_name, 'w') as out: 
     out.writelines(lines) 

PS我沒有創建此,原帖在這裏Editing specific line in text file in python

我會建議使用的登錄信息SQL數據庫不過,如果你想使用SQL我會建議使用sqlite3的庫/模塊

此外,您的程序有可能無法「記住我的詳細信息」,因爲您將細節存儲爲由用戶輸入更改的變量,該變量存儲在RAM中。一旦程序關閉,該數據就會被清除,因此如果通過用戶輸入更改該數據,則每次關閉程序時都必須重新更改輸入。

您也可以掃描文件中的字符串,例如用戶名。 Search for string in txt file Python

相關問題