V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
chashao
V2EX  ›  问与答

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

  •  
  •   chashao · May 23, 2018 · 958 views
    This topic created in 2909 days ago, the information mentioned may be changed or developed.

    代码如下

    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  
       May 23, 2018
    'wr' 是什么鬼。。用 'w+' 或者 'r+'
    gjquoiai
        2
    gjquoiai  
       May 23, 2018   ❤️ 1
    _(:з)∠)_ 修正。。用 ‘ r+’
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3067 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 12:57 · PVG 20:57 · LAX 05:57 · JFK 08:57
    ♥ Do have faith in what you're doing.