我有一个包含十个文件的文件夹,我想循环遍历这些文件。当我打印出文件名时,我的代码可以正常工作:
我有一个文件夹里有十个文件,我想要循环遍历这些文件。当我打印出文件名的时候,我的代码运行良好:
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()
函数?