首页 新闻 会员 周边

python创建文件

0
悬赏园豆:15 [已解决问题] 解决于 2017-07-26 20:10

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,应该是第五行的问题,请问如何解决

skrrr的主页 skrrr | 初学一级 | 园豆:110
提问于:2017-07-26 17:20
< >
分享
最佳答案
0
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'

收获园豆:15
悟行 | 专家六级 |园豆:12559 | 2017-07-26 17:49
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册