擅长:python、mysql、java
<p>这是因为<a href="https://docs.python.org/3/library/os.html#os.listdir" rel="nofollow noreferrer">^{<cd1>}</a>不返回文件的完整路径,只返回文件名部分;也就是<code>'foo.txt'</code>,当打开时需要<code>'E:/somedir/foo.txt'</code>,因为文件不存在于当前目录中。</p>
<p>使用<a href="https://docs.python.org/3/library/os.path.html#os.path.join" rel="nofollow noreferrer">^{<cd4>}</a>将目录预先设置为文件名:</p>
<pre><code>path = r'E:/somedir'
for filename in os.listdir(path):
with open(os.path.join(path, filename)) as f:
... # process the file
</code></pre>
<p>(另外,您没有关闭文件,<code>with</code>块将自动处理它)。</p>