chashao
V2EX  ›  问与答

Python with-statement 中出现异常并捕获,在 except 出错,能帮我看看为啥么?

By chashao at 2018 年 5 月 23 日 · 1219 次点击

代码如下

with open(tombstone, 'wr') as fp:
    try:
        tomb = json.load(fp)
    except ValueError as e:
        tomb = {"event_id": 0,
                       "event_sec": 0,
                       "event_micro": 0}
        json.dump(tomb, fp)

tombstone 是一个 json 文件,它是空的时候就会抛出 ValueError 错误,所以我想在 except 中建一个新的,然后写到原来的文件 tombstone 中,但是会在 json.dump 中出现 IOError: [Errno 9] Bad file descriptor 是因为报错就会使得 fp 进行__exit__(),然后被关闭么? 还有就是我这么写符合逻辑么? 我想出的修改方案是下面这样.

    with open(tombstone, 'r') as fr:
        try:
            tomb = json.load(fr)
        except ValueError as e:
            with open(tombstone, "w") as fw:
                tomb = {"event_id": 0,
                        "event_sec": 0,
                        "event_micro": 0}
                json.dump(tomb, fw)
2 条回复
gjquoiai
   1
gjquoiai  
   2018 年 5 月 23 日
'wr' 是什么鬼。。用 'w+' 或者 'r+'
gjquoiai
   2
gjquoiai  
   2018 年 5 月 23 日   ❤️ 1
_(:з)∠)_ 修正。。用 ‘ r+’
© 2026 V2EX · 26ms · 3.9.8.5