我有一个文件夹,里面有十个文件,我想循环访问。当我打印出文件名时,我的代码可以正常工作:
import os
indir = '/home/des/test'
for root, dirs, filenames in os.walk(indir):
for f in filenames:
print(f)
哪个打印:
1
2
3
4
5
6
7
8
9
10
但是如果我尝试在循环中打开文件,我会收到一个 IO 错误:
import os
indir = '/home/des/test'
for root, dirs, filenames in os.walk(indir):
for f in filenames:
log = open(f, 'r')
Traceback (most recent call last):
File "/home/des/my_python_progs/loop_over_dir.py", line 6, in <module>
log = open(f, 'r')
IOError: [Errno 2] No such file or directory: '1'
>>>
即使在循环内部,我是否也需要将文件的完整路径传递给open()
他们?