擅长:python、mysql、java
<p>您需要编辑remove部分,以便它优雅地处理不存在的案例。你知道吗</p>
<pre><code>import os
try:
fn = 'data.tmp'
with open(fn) as f:
data = json.load(f)
except:
try:
if os.stat(fn).st_size > 0:
os.remove(fn) if os.path.exists(fn) else None
except OSError as e: # this would be "except OSError, e:" before Python 2.6
if e.errno != errno.ENOENT:
raise
</code></pre>
<p>另见<a href="https://stackoverflow.com/questions/10840533/most-pythonic-way-to-delete-a-file-which-may-not-exist">Most pythonic way to delete a file which may not exist</a></p>
<p>您可以在单独的函数中提取静默删除。你知道吗</p>
<p>同样,从另一个同样的问题:</p>
<pre><code># python3.4 and above
import contextlib, os
try:
fn = 'data.tmp'
with open(fn) as f:
data = json.load(f)
except:
with contextlib.suppress(FileNotFoundError):
if os.stat(fn).st_size > 0:
os.remove(fn)
</code></pre>
<p>我个人更喜欢后一种方法——它是明确的。你知道吗</p>