首页 > 解决方案 > 将输入传递给 json 以打开正确的 json 文件

问题描述

代替

if self.x == '111' and self.y == '':
    with open('111.json', 'r') as fp:
        data = json.load(fp)

else self.x == '149' and self.y == '':
    with open('149.json', 'r') as fp:
        data = json.load(fp)

我该怎么做这样的事情?

#input get from user
input = 149
if self.y == '':
    with open('input.json', 'r') as fp:
        data = json.load(fp)

我正在尝试获取输入以确定要读取的文件,我尝试了一些方法,例如(input).jsonor(self.y).json但它向我显示“AttributeError:'str'对象没有属性'json'”。

请提供任何帮助。

标签: python

解决方案


您需要使用f 字符串

x = input("Enter : ")
if self.y == '':
    with open(f'{x}.json', 'r') as fp:
        data = json.load(fp)

推荐阅读