要求用户创建新的用户名,因为该文件已存在

时间:2015-09-29 07:57:52

标签: python-2.7 save file-exists

基于该计划。它可以保存文件取决于用户输入的用户名。如何使程序要求用户更改为其他用户名,因为用户名已经存在。

while True:
RegOrLog = raw_input('[Register/Login]:')
if RegOrLog not in ('reg', 'register', 'REGISTER','log', 'login', 'LOGIN',\
                    'r','l'):
    print "Please enter 'register' if you dont have account"
    print "Please enter 'login' if you already registered"

if RegOrLog in ('reg', 'register', 'REGISTER','r','Register'):
    count = 0
    while count < 1:
        regusrnm = raw_input('Enter your desire login name:')
        regusrnm = regusrnm.lower()
        regpswrd = raw_input('Enter your password:')
        while True:
            regage = raw_input('Enter your age:')
            if int(regage) not in range(1, 100):
                print 'please enter apropriate value'
            else:
                break

        while True:
            reggender = raw_input('State your gender:')
            if reggender not in ('male', 'female'):
                print 'Are you an alien?'
            else:
                break

        data = {"username": regusrnm, "password": regpswrd, "age": regage,\
                "gender": reggender}
        pickle.dump( data, open( regusrnm, "wb" ) )
        RegOrLog = 'login'
        print 'Please login to your account for security purpose'
        break

if RegOrLog in ('log', 'login', 'LOGIN','l','Login'):
    logusrnm = raw_input('Enter your username:')
    data = pickle.load( open( logusrnm, "rb" ) )
    count = 3
    while count >= 1:
        logpswrd = raw_input('Enter your password:')
        count = count - 1
        if logpswrd != data["password"]:
            print "You have",count, "attempt left"
            if count == 0:
                print "The account doesn't exist or wrong password"
                print 'Please register a new one'
                break

        else:
            print 'Welcome Back',data["username"]
            break

以及如何使保存文件存储在文件夹中,以免弄乱它。喜欢干净整洁:D

1 个答案:

答案 0 :(得分:1)

import os.path
os.path.exists(file_name) 

如果存在名称为True的目录或文件,则返回file_name。所以你只需检查

if os.path.exists(regusrnm) == True:
    # ask user to enter another name

这意味着你改变了

if RegOrLog in ('reg', 'register', 'REGISTER','r','Register'):
    count = 0
    while count < 1:

if RegOrLog in ('reg', 'register', 'REGISTER','r','Register'):
    count = 0
    while os.path.exists(regusrnm) == True:

在此之前,您需要为regusrnm分配一些值。 admin似乎很好,因为每个系统都有admin:)

所以整个部分都是

regusrnm = 'admin'
if RegOrLog in ('reg', 'register', 'REGISTER','r','Register'):
    count = 0
    while os.path.exists(regusrnm) == True:

您还可以使用os.path.isfile(file_name)检查file_name是否为文件(而不是目录)。