为什么文件上下文无法从txt文件读取?

时间:2019-05-07 08:15:03

标签: python

我创建了一个新的空txt文件,但是下面的代码对其进行了读取和写入。

f = open('users.txt', 'r+')
users = eval(f.read())  #f.read()read a string,eval()transfer string to dict
for i in range(4):
    name = input('Input Username: ')
    passwd = input('Input password: ')
    c_passwd = input('Confirm password again: ')
    if len(name.strip()) != 0 and name not in users and len(passwd.strip()) != 0 and passwd == c_passwd:
        users[name]= {'passwd':passwd, 'role':1} #insert new data, role 1: Customer; role 2: Restaurant; role 3: Admin
        f.seek(0)
        f.truncate()  #clear file
        f.writelines(str(users)) #write data to file from dict
        print('Congratulations, Register Success. ')
        f.close()
        break
    elif len(name.strip()) == 0:
        print('Username could not be empty. Remain %d chance' %(3-i))
    elif name in users:
        print('Username repeat. Remain %d chance' %(3-i))
    elif len(passwd.strip()) == 0:
        print('Password could not be empty. Remain %d chance' %(3-i))
    elif c_passwd != passwd:
        print('Password not same. Remain %d chance' %(3-i))

#log in
f = open('users.txt', 'r', encoding='utf8')
users = eval(f.read())
for count in range(3):
    name = input('Input Username: ')
    password = input('Input password: ')
    if name in users and password == users[name]['passwd']:
        print('Log in successful!')
        break
    else:
        print('Username or/and Password is/are wrong,You still have %d chance'%(2-count))
f.close()

系统显示

Traceback (most recent call last):
  File "C:/Users/zskjames/PycharmProjects/Fit5136/Register, log in.py", line 4, in <module>
    users = eval(f.read()) #f.read()read a string,eval()transfer string to dict
  File "<string>", line 0

    ^
SyntaxError: unexpected EOF while parsing

有人可以告诉我如何解决该问题吗?以及将来如何避免这种错误。

1 个答案:

答案 0 :(得分:1)

您可能希望文本文件包含JSON,以便轻松与之交互并将其转换为dict

为此,您需要将eval替换为json.load

import json

with open('users.txt', 'r+') as f:
    users = json.load(f)
    # rest of your code

为使其正常工作,您的文本文件应类似于以下内容:

{"John Doe": {"passwd": "somepass", "role": 1}}

此外,您需要替换:

f.writelines(str(users)) #write data to file from dict

收件人:

json.dump(users, f)