擅长:python、mysql、java
<p>试试这个:</p>
<pre><code>from __future__ import print_statement
import sys
if os.path.exists(x):
with open(x, 'r') as f:
# Do Stuff with file
else:
print("No such file '{}'".format(x), file=sys.stderr)
</code></pre>
<p>这里的目标是尽可能清楚发生了什么。我们首先通过调用<code>os.path.exists(x)</code>来检查文件是否存在。这将返回True或False,允许我们在<code>if</code>语句中简单地使用它。</p>
<p>从那里你可以打开文件阅读,或处理退出你喜欢。使用Python3样式的打印函数可以显式声明输出的位置,在本例中是stderr。</p>