V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
chashao
V2EX  ›  问与答

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

  •  
  •   chashao · 2018-05-23 18:39:58 +08:00 · 625 次点击
    这是一个创建于 2179 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码如下

    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)
    
    gjquoiai
        1
    gjquoiai  
       2018-05-23 19:16:09 +08:00
    'wr' 是什么鬼。。用 'w+' 或者 'r+'
    gjquoiai
        2
    gjquoiai  
       2018-05-23 19:18:07 +08:00   ❤️ 1
    _(:з)∠)_ 修正。。用 ‘ r+’
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3189 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 13:54 · PVG 21:54 · LAX 06:54 · JFK 09:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.