python - 将输入传递给 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).json
or(self.y).json
但它向我显示“AttributeError:'str'对象没有属性'json'”。
请提供任何帮助。
解决方案
您需要使用f 字符串
x = input("Enter : ")
if self.y == '':
with open(f'{x}.json', 'r') as fp:
data = json.load(fp)
推荐阅读
- scala - Azure Databricks Scala:如何替换相应层次结构之后的行
- php - 当我尝试获得一对一的关联值时,为什么我在 Laravel 中的关系会倒退?
- javascript - 获取具有特定属性 axios 的数组对象
- node.js - 用 Jest 查询内存中的 mongodb
- css - 删除一个单元格中的表格背景
- java - Android MediaPlayer 返回 Prepare failed.: status=0x1 on device 但在模拟器中运行
- ubuntu - 无法从 Ubuntu 通过以太网 ping Beaglebone Black
- php - 如何将凭据安全地存储在 php 文件中
- javascript - 离子滑块固定在离子含量的底部
- python - 使用 GStreamer/OpenCV 进行旋转,延迟时间不会大幅增加(Jetson Nano、OpenCV 4.1、GStreamer 1.0、Python)