如何将输入保存到文件,然后检查文件中的输入?

2024-09-28 01:30:54 发布

您现在位置:Python中文网/ 问答频道 /正文

为了好玩,我尝试创建一个非常基本的小操作系统,使用Python。到目前为止,我有:

rUsername = input("Create a new user: ")
rPassword = input("Create a password for the user: ")
tUsername = input("Username: ")

def username():
    if tUsername != rUsername:
        print("User not found.")
        blank = input("")
        exit()
username()

def password():
    if tPassword != rPassword:
        print("Incorrect password.")
        blank = input("")
        exit()
tPassword = input("Password: ")

password()

def typer():
    typerCMD = input("")

print ("Hello, and welcome to your new operating system. Type 'help' to get started.")
shell = input("--")
if shell == ("help"):
    print("Use the 'leave' command to shut down the system. Use the 'type' command to start a text editor.")
shell2 = input ("--")
if shell2 == ("leave"):
    print("Shutting down...")
    exit()
if shell2 == ("type"):
    typer()

但我希望程序运行,这样它将保存创建的用户名到一个文件,这样你就不必创建一个新的用户名,每次你运行它。有什么建议吗?(请不要用我的“文本编辑器”来评判我,那只是为了登录的目的。)


Tags: thetonewinputifdefcreateexit
3条回答

以下是创建用户和检查系统中是否存在用户的功能。你知道吗

我们使用Pickle库以字典结构存储用户详细信息。你知道吗

演示代码:

import os
import pickle
user_details_file = "user_details1.txt"

def createNewUser():
    """
        Create New USer.
        1. Accept USer name and PAssword from the User.
        2. Save USer Name and Password to File.
    """
    #- Check Login Detail file is present or not.
    if os.path.isfile(user_details_file):
        #- Load file into dictionary format.
        fp = open(user_details_file, "rb")
        data = pickle.load(fp)
        fp.close()
    else:
        #- Set empty dictionary when user details file is not found.
        data = {}

    while 1:
        username = raw_input("Enter Username:").strip()
        if username in data:
            print "User already exist in system. try again"
            continue

        password = raw_input("Enter password:")
        data[username] = password

        #- Save New user details in a file.   
        fp = open(user_details_file, "wb")
        pickle.dump(data, fp)
        fp.close()
        return True


def loginUSer():
    """
        Login User.
        1. Open  User Name and Password file.
        2. Accept User name and Password from the User.
        3. check User is present or not
    """    
    #- Check Login Detail file is present or not. 
    if os.path.isfile(user_details_file):
        fp = open(user_details_file, "rb")
        data = pickle.load(fp)
        fp.close()
    else:
        #- Load file into dictionary format.
        # We can return False from here also but why to tell user that your are first user of this application.
        data = {}

    username = raw_input("Enter Username:").strip()
    password = raw_input("Enter password:").strip()
    if username in data and password==data["username"]:
        print "You login"
        return True
    else:
        print "No user worong username or password"
        return False



if __name__=="__main__":
    new_userflag = raw_input("you want to create new user? yes/no").lower()
    if new_userflag=="yes":
        createNewUser()

    loginUSer()

注意:

  1. python2.x中使用了raw\u input()
  2. 在python3.x中使用的input

链接很少

  1. File modes to read and write
  2. Pickling and Unpicking

你可以这样写一个文件

with open('myfile.txt', 'w') as f:
    f.write(rUsername)

一个简单的程序,它要求用户输入用户名,并检查用户名是否在文件中,如果不存在,它会将用户名写入文件,从而创建一个新的用户,用这个逻辑你应该在路上

while True:
    username = input('please enter your username or exit to quit the program')

    if username == 'exit':
        break
    else:

        with open('myfile.txt', 'r') as f:
            for line in f:
                print(line)
                if username == line:
                    print('you belong here')
                    break
            else:
                with open('myfile.txt', 'a') as f:
                    f.write(username)
                    print('You dont belong but your name has been saved')
                    break

您可以创建用户名和相应密码的字典,然后将其保存到json文件中。你知道吗

假设你的辞典是这样的

user_dict = {rUsername : rPassword}

保存到文件“用户.json“即写操作

import json
with open("users.json", "w") as f:
    json.dumps(user_dict,f)

读取操作

import json
with open("users.json", "r") as f:
     user_dict = json.loads(f)

相关问题 更多 >

    热门问题