擅长:python、mysql、java
<p>为了补充Beri提供的代码,我宁愿使用try/except语句和新样式的字符串格式:</p>
<pre><code>print("Opening and closing a file")
f_name = 'jub.txt'
try:
with open(f_name, 'r') as text_file:
print(text_file.read())
except FileNotFoundError:
print("File {} does not exist".format(f_name))
</code></pre>
<p>顺便说一下,我建议您直接阅读官方的Python doc,它非常清晰简洁:</p>
<p><a href="https://docs.python.org/3.4/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">https://docs.python.org/3.4/tutorial/inputoutput.html#reading-and-writing-files</a></p>