bal*_*der 62 python file-io absolute-path
我有一个包含十个文件的文件夹,我想循环播放.当我打印出文件的名称时,我的代码工作正常:
import os
indir = '/home/des/test'
for root, dirs, filenames in os.walk(indir):
for f in filenames:
print(f)
Run Code Online (Sandbox Code Playgroud)
哪个印刷品:
1
2
3
4
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)
但是如果我尝试在循环中打开文件,我会收到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'
>>>
Run Code Online (Sandbox Code Playgroud)
我是否需要在循环内部传递文件的完整路径open()
?
Lev*_*von 92
如果您只是在单个目录中查找文件(即您没有尝试遍历目录树,它看起来不像),为什么不简单地使用os.listdir():
import os
for fn in os.listdir('.'):
if os.path.isfile(fn):
print (fn)
Run Code Online (Sandbox Code Playgroud)
代替os.walk().您可以将目录路径指定为os.listdir()的参数.os.path.isfile()将确定给定的文件名是否用于文件.
kob*_*las 26
是的,你需要完整的路径.
log = open(os.path.join(root, f), 'r')
Run Code Online (Sandbox Code Playgroud)
是快速修复.正如评论指出的那样,os.walk
降级为子目录,因此您需要使用当前目录根而不是indir
路径连接的基础.
小智 8
您必须指定您正在处理的路径:
source = '/home/test/py_test/'
for root, dirs, filenames in os.walk(source):
for f in filenames:
print f
fullpath = os.path.join(source, f)
log = open(fullpath, 'r')
Run Code Online (Sandbox Code Playgroud)