【问题标题】:creating new json file when button is clicked单击按钮时创建新的json文件
【发布时间】:2020-03-24 00:12:22
【问题描述】:

打开我的应用程序时,它会加载一个 config.json 文件。

def load_profiledata(self):
    self.log_print("Loading profiles...")
    self.config = {}
    try:
        with open('./config.json', 'r+') as f:
            self.config = json.load(f)

        self.container.value_prof.set(self.config['prof'])
        self.container.value_name.set(self.config['name'])
        self.container.value_email.set(self.config['email'])
        self.container.value_phone.set(self.config['phone'])
        self.container.value_addr1.set(self.config['addr1'])
        self.container.value_addr2.set(self.config['addr2'])
        self.container.value_zip.set(self.config['zip'])
        self.container.value_cardnumber.set(self.config['cardnumber'])
        self.container.value_cardexpmonth.set(self.config['cardexpmonth'])
        self.container.value_cardexpyear.set(self.config['cardexpyear'])
        self.container.value_cardcode.set(self.config['cardcode'])
        self.log_print("loaded config.json")
    except Exception:
        self.log_print("failed to load profile")
        self.save_profile()

我需要在我的 gui 中使用 save_profile 按钮来生成具有相同字段的新 json 文件。

def save_profile(self):
    self.config['prof'] = self.container.value_prof.get()
    self.config['name'] = self.container.value_name.get()
    self.config['email'] = self.container.value_email.get()
    self.config['phone'] = self.container.value_phone.get()
    self.config['addr1'] = self.container.value_addr1.get()
    self.config['addr2'] = self.container.value_addr2.get()
    self.config['zip'] = self.container.value_zip.get()
    self.config['cardnumber'] = self.container.value_cardnumber.get()
    self.config['cardexpmonth'] = self.container.value_cardexpmonth.get()
    self.config['cardexpyear'] = self.container.value_cardexpyear.get()
    self.config['cardcode'] = self.container.value_cardcode.get()
    with open('./config.json', 'w') as f:
        json.dump(self.config, f)

    self.log_print("profile saved")
    self.profiles_print(self.container.value_prof.get())   

如何生成一个新的 json 文件,文件名的值为self.container.value_prof.get()?这是任何可能的......在python中

感谢您的帮助。 谢谢!

【问题讨论】:

  • fname = self.container.value_prof.get()with open(f"{fname}.json") as f
  • 谢谢!所以我添加了fname = self.container.value_prof.get() 并将with open('./config.json', 'w') as f: 更改为with open(f"{fname}.json") as f:,现在出现“没有这样的文件或目录”错误。
  • 你仍然需要使用, 'w'并打开文件进行写入。
  • !! tysm,你们俩

标签: python json tkinter tkinter-entry


【解决方案1】:

fname = self.container.value_prof.get() 使文件名成为我想要的值

with open(f"{fname}.json", 'w') as f:改名

感谢@frost-nzcr4 和@Karl Knechtel

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 2011-03-05
    • 2012-08-29
    • 1970-01-01
    相关资源
    最近更新 更多