写入文本文件格式

时间:2020-08-06 19:52:04

标签: python python-3.x formatting

我分配了一个简单的任务管理器/任务列表。该代码块只是该程序处理登录,新用户名和密码注册的部分。当用户注册时,该输入将写入名为user.txt的文本文件。

无论何时写入文本文件,它都将这样写:(['admin', 'adm1n']) 相反,它应该这样写:admin, adm1n

user_file = open("user.txt","r+")
login = False

while login == False:
new = input("Are you a new user? Y/N:\n").lower()

if new == "y":
    print("Please register a new username and password:\n")
    new_user1 = input("Please enter a new username:\n").split()
    new_pass1 = input("Please enter a new password:\n").split()
    new_user2 = input("Please confirm your username:\n").split()
    new_pass2 = input("Please confirm your password:\n").split()
    user_pass1 = new_user1 , new_pass1
    user_pass2 = new_user2 , new_pass2
    if user_pass1 == user_pass2:
        user_file.write(f"{user_pass2},")
        user_file.seek(0)
    break

elif new == "n":
    username = input("Enter your username:\n")
    password = input("Enter your password:\n")
    valid_user = username
    valid_password = password
    
for line in user_file:
    valid_user, valid_password = line.split(", ")
    if username == valid_user and password == valid_password:
        login = True

if login == False:
    print("Incorrect details! Please enter a valid username and password")

我在做什么错?我敢肯定它很小。 预先感谢!

2 个答案:

答案 0 :(得分:2)

因为您正在那里创建一个元组。相反,您应该创建一个字符串。这是您的代码的更正版本

    user_pass1 = new_user1 + ',' + new_pass1
    user_pass2 = new_user2 + ',' + new_pass2
    if user_pass1 == user_pass2:
        user_file.write(f"{user_pass2},")
        user_file.seek(0)
    break

答案 1 :(得分:0)

感谢大家的反馈。

我设法弄清楚了。我向它添加了一个索引以打印字符串,并且效果很好。

    user_pass2 = new_user2 , new_pass2
    if user_pass1 == user_pass2:
        #Writes username and password to text file in format requested.
        user_file.write(f'\n{user_pass2[0]}, {user_pass2[1]}')