擅长:python、mysql、java
<p>编写<code>open(file)</code>时,Python试图在启动解释器的目录中找到文件<code>tc.out</code>。您应该在“打开”中使用该文件的完整路径:</p>
<pre><code>with open(os.path.join(root, file)) as f:
</code></pre>
<p>让我举个例子来说明:</p>
<p>我在目录<code>/tmp/sto/deep/</code>中有一个名为“somefile.txt”的文件(这是一个Unix系统,所以我使用正斜杠)。然后我有一个简单的脚本,它位于目录<code>/tmp</code>:</p>
<pre><code>oliver@armstrong:/tmp$ cat myscript.py
import os
rootdir = '/tmp'
for root, dirs, files in os.walk(rootdir):
for fname in files:
if fname == 'somefile.txt':
with open(os.path.join(root, fname)) as f:
print('Filename: %s' % fname)
print('directory: %s' % root)
print(f.read())
</code></pre>
<p>当我从<code>/tmp</code>目录执行这个脚本时,您将看到<code>fname</code>只是文件名,指向它的路径是ommitted。这就是为什么您需要将它与来自<code>os.walk</code>的第一个返回参数连接起来。</p>
<pre><code>oliver@armstrong:/tmp$ python myscript.py
Filename: somefile.txt
directory: /tmp/sto/deep
contents
</code></pre>