代码如下
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)
|      1gjquoiai      2018-05-23 19:16:09 +08:00 'wr' 是什么鬼。。用 'w+' 或者 'r+' | 
|      2gjquoiai      2018-05-23 19:18:07 +08:00  1 _(:з)∠)_ 修正。。用 ‘ r+’ |