nin*_*ine 2 python dictionary file python-3.x
我目前正在用Python编写帐户注册程序。该程序使用一个名为的文件players,该文件中写入了一个字典,字典中包含与玩家用户名相对应的键,以及其他信息(电子邮件,密码,年龄和性别)作为与相应键相关联的数组。
该accounts字典的定义是如此取决于是否players文件存在,它是空的。
def is_file_empty(filename):
    return os.stat(filename).st_size == 0
def create_file(filename, mode = 'w'):
    f = open(filename, mode)
    f.close()
if os.path.exists('players'):
    with open('players', 'r') as f:
        if is_file_empty('players'):
            accounts = {}
        else:
            accounts = ast.literal_eval(f.read())
else:
    create_file('players')
    accounts = {}
然后使用Player类内部的函数将其写入文件。
def write(self):
        accounts[self.name] = [self.email, self.password, self.age, self.gender]
        with open('players', 'w') as f:
            f.write(accounts)
它工作正常,但是由于编写方式的原因,它始终只占一行。我想尝试在字典中的每一行上编写每个键/值对,但是我完全不知道如何实现这一点。
我该怎么办?
如果我建议使用其他方法,请使用现有的简单序列化方案(如JSON或YAML),而不要手动滚动自己的序列化方案:
import json
try:
    with open('players.json', 'r') as file:
        accounts = json.load(file)
except (OSError, ValueError):  # file does not exist or is empty/invalid
    accounts = {}
# do something with accounts
with open('players.json', 'w') as file:
    json.dump(accounts, file, indent=2)
| 归档时间: | 
 | 
| 查看次数: | 3396 次 | 
| 最近记录: |