擅长:python、mysql、java
<p>首先检查您的文件是否存在于当前目录中,您可以添加这个简单的验证。
第二,与包装器一起使用,它将在您退出此块后为您关闭文件。第三:使用read和readlines方法读取文件。你知道吗</p>
<pre><code>print ("Opening and closing a file")
f_name = "jub.txt"
if not os.path.exists(f_name):
print 'File %s does not exist'%f_name
return
with open(f_name , "r") as text_file:
print (text_file.read())
</code></pre>
<p>为了使路径更精确,可以使用完整的系统路径,而不是相对路径。示例:'/home/my\u user/doc/myfile.txt文件'</p>