import json
class User():
def __init__(self, username):
self.username = username
file_name = 'self.username.json'
try:
with open(file_name) as fi:
name = json.load(fi)
except FileNotFoundError:
with open(file_name, 'w') as fi:
json.dump(self.username, fi)
print("back in any time")
else:
print("welcome back " + name)
User('bb')
我输入的变量是bb,结果生成的文件还是self.username.json,应该是第五行的问题,请问如何解决
import json class User(): def __init__(self, username): self.username = username file_name = self.username + '.json' try: with open(file_name) as fi: name = json.load(fi) except FileNotFoundError: with open(file_name, 'w') as fi: json.dump(self.username, fi) print("back in any time") else: print("welcome back " + name) User('bb')
file_name = 'self.username.json' 改成 file_name = self.username + '.json'