我有一个json文件,加载到一个变量中,如果这个文件不存在,我会做一个字典,很快就会变成json文件,很好,我试着寻找字典中的特定元素,这就是为什么我使用生成器表达式。
我是这样使用它的:
Data = json.load(open(file)) if isfile("data.json") else {"News": {},"Records": {},"Profiles": []}
name = "asdadsefttytryrty"
get = next(get for get in Data["Profiles"] if get["Name"] == name or get["ID"] == name)
字典data
应该是这样的
{
"News": {},
"Records": {},
"Profiles": [
{
"Name": "123rd453",
"ID": "1",
"Password": "dfsdfee",
"Image": "image"
},
{
"Name": "asdadsefttytryrty",
"ID": "2",
"Password": "12345",
"Image": "image"
}
]
}
好吧,如果我找的元素不存在,这就有问题了:停止迭代
所以为了检查元素是否存在,我想用if-else来执行某些操作,但是我做不到,所以我决定用try-except作为临时解决方案,我认为它不可靠。
Data = json.load(open(file)) if isfile("data.json") else {"News": {},"Records": {},"Profiles": []}
name = "asdadsefttytryrty"
try:
get = next(get for get in Data["Profiles"] if get["Name"] == name or get["ID"] == name)
print("exist")
except:
print("Doesn't exist")
这样做是正确的吗?
2条答案
按热度按时间gg58donl1#
不要把事情搞复杂,你可以简单地这样做:
使用
os
模块中的path.exists()
方法检查某个路径是否存在。在一开始就声明变量是一个很好的做法。
4ioopgfo2#
next
在给定的迭代器耗尽时确实会引发StopIteration
,所以您所做的基本上是正确和可靠的,唯一要添加的是您所期望的特定异常,以便不捕获诸如KeyboardInterrupt
之类的意外异常:也就是说,在这种情况下,使用
for-else
结构编写的代码可能会更干净、更可读: