Нужен Python, чтобы удалить все после запятой во внешнем файле при проверке ввода пользователя - PullRequest
0 голосов
/ 13 февраля 2019

Итак, мне нужен мой код на Python для чтения каждой строки из внешнего файла и удаления всего после запятой.Затем он должен проверить ввод пользователя с новой строкой.

Точно так же, как процесс проверки, где пользователь регистрируется, а затем код проверяет, взято ли имя пользователя

Но во внешнемфайл, данные пользователя хранятся в виде: 'username, password'

Вот мой код:

    LogFile = 'accounts.txt'
    invalidUserName = False
    Uusername = input("Please enter your desired username: ")
    while len(Uusername) < 3 or len(Uusername) > 16:
        Uusername = input("Username is not between the length of 3 and 16, please re-enter: ")

    with open(LogFile) as f:
        content = f.readlines()
        contnt = [l.strip() for l in content if l.strip()]
        passlist = []
        userlist = []
        for line in content:
            try:
                userlist.append(line.split(",")[0])
                passlist.append(line.split(",")[1])
            except IndexError:
                pass
        for username in userlist:
            while username == Uusername:
                Uusername = input(('Username is taken, please enter another one: '))
                invalidUserName = True

    if not invalidUserName:
        password = input("Please enter your desired password: ")
        while len(password) < 3 or len(password) > 16:
            password = input("Password is not between the length of 3 and 16, please re-enter: ")
        while password == username:
            password = input("Password cannot be the same as the username, please re-enter: ")
        VerPW = input("Please verify your password: ")
        while VerPW != password:
            VerPW = input("Passwords do not match, try again: ")
        file = open ('accounts.txt','a')
        file.write (username +','+password + "\n")
        file.flush()
        file.close
        print ("Details stored successfully")

После строки 5 мне нужен код для проверки имен пользователей из внешнего файла, безвсе после запятых и попросить пользователя ввести еще раз, если имя пользователя уже существует

1 Ответ

0 голосов
/ 13 февраля 2019

list.txt:

emkay,123
alibaba,420

khanbaba,5647
naughty_princess,3242
whatthehack,657

и затем:

logFile = "list.txt"

with open(logFile) as f:
    content = f.readlines()

# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]


# list to store the passwords
passList = []

# list to store the usernames
userList = []
for line in content:
    userList.append(line.split(",")[0])
    passList.append(line.split(",")[1])


print(userList)
print(passList)

user_inp = input("Enter a username: ")

for username in userList:
    if username == user_inp:
        print("Username: {}, already taken. Please try a different username".format(username))

ВЫХОД:

['emkay', 'alibaba', 'khanbaba', 'naughty_princess', 'whatthehack']
['123', '420', '5647', '3242', '657']
Enter a username: naughty_princess
Username: naughty_princess, already taken. Please try a different username

РЕДАКТИРОВАНИЕ:

Если вы хотите, чтобы цикл остановился, когда имя пользователя найдено.просто, break прочь.

for username in userList:
    if username == user_inp:
        print("Username: {}, already taken. Please try a different username".format(username))
        break

РЕДАКТИРОВАТЬ 2:

, чтобы применить это в только что опубликованном коде,

if username == Uusername:
       Uusername = ('Username is taken, please enter another one: ')
       break     # or use continue as it looks like you need it

РЕДАКТИРОВАТЬ 3:

Ваш код исправлен, вам нужен логический флаг для недопустимых пользователей и действовать следующим образом:

LogFile = 'accounts.txt'
invalidUserName = False
Uusername = input("Please enter your desired username: ")
while len(Uusername) < 3 or len(Uusername) > 16:
    Uusername = input("Username is not between the length of 3 and 16, please re-enter: ")

with open(LogFile) as f:
    content = f.readlines()
    contnt = [l.strip() for l in content if l.strip()]
    passlist = []
    userlist = []
    for line in content:
        try:
            userlist.append(line.split(",")[0])
            passlist.append(line.split(",")[1])
        except IndexError:
            pass
    print(userlist)
    for username in userlist:
        if username == Uusername:
            print('Username is taken, please enter another one:')
            invalidUserName = True
            break
if not invalidUserName:
    password = input("Please enter your desired password: ")
    while len(password) < 3 or len(password) > 16:
        password = input("Password is not between the length of 3 and 16, please re-enter: ")
    while password == username:
        password = input("Password cannot be the same as the username, please re-enter: ")
    VerPW = input("Please verify your password: ")
    while VerPW != password:
        VerPW = input("Passwords do not match, try again: ")
    file = open ('accounts.txt','a')
    file.write (username +','+password + "\n")
    file.flush()
    file.close
    print ("Details stored successfully")

РЕДАКТИРОВАТЬ 4:

LogFile = 'accounts.txt'
invalidUserName = False
while True:
    Uusername = input("Please enter your desired username: ")
    while len(Uusername) < 3 or len(Uusername) > 16:
        Uusername = input("Username is not between the length of 3 and 16, please re-enter: ")

    with open(LogFile) as f:
        content = f.readlines()
        contnt = [l.strip() for l in content if l.strip()]
        passlist = []
        userlist = []
        for line in content:
            try:
                userlist.append(line.split(",")[0])
                passlist.append(line.split(",")[1])
            except IndexError:
                pass
        print(userlist)
        for username in userlist:
            if username == Uusername:
                print('Username is taken, please enter another one:')
                invalidUserName = True
                break
    if not invalidUserName:
        password = input("Please enter your desired password: ")
        while len(password) < 3 or len(password) > 16:
            password = input("Password is not between the length of 3 and 16, please re-enter: ")
        while password == username:
            password = input("Password cannot be the same as the username, please re-enter: ")
        VerPW = input("Please verify your password: ")
        while VerPW != password:
            VerPW = input("Passwords do not match, try again: ")
        file = open ('accounts.txt','a')
        file.write (username +','+password + "\n")
        file.flush()
        file.close
        print ("Details stored successfully")

        exit_now = input("Press 1 to exit")

        if '1' in exit_now:
            break
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...