您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 正确使用os.path和os.join

5b51 2022/1/14 8:22:07 python 字数 1968 阅读 563 来源 www.jb51.cc/python

我正在尝试编写一个处理各种子目录中的文件的处理程序,但是当我的脚本可以看到这些文件时,它无法对它们做任何事情,因为它无法组装它们的路径. 有问题的部分来自这个循环: for (path, dirs, files) in os.walk("data/"): for image in files: #do something to the image 现在,该脚本在数据目录的

概述

有问题的部分来自这个循环:

for (path,dirs,files) in os.walk("data/"):
    for image in files: 
        #do something to the image

现在,该脚本在数据目录的第一级工作,但无法处理数据的子目录.

我尝试使用os.path.join():

for (path,files) in os.walk("data/"):
    print os.path.join(path,dirs)

但是这引发了以下情况:

Traceback (most recent call last):
  File "bench.py",line 26,in <module>
    print os.path.join(path,dirs)
  File "/usr/lib/python2.7/posixpath.py",line 75,in join
    if b.startswith('/'):
AttributeError: 'list' object has no attribute 'startswith'

简而言之,我想要做的是组装从数据到图像的路径,其中包括数据的子目录.这样做的最佳做法是什么?

for path,files in os.walk('data/'):
    for f in files:
        fname = os.path.join(path,f)
        assert(os.path.exists(fname))

dirs是目录路径中的目录列表.你可以实际修改dirs以防止os.walk进入某些目录(整洁!).

总结

以上是编程之家为你收集整理的python – 正确使用os.path和os.join全部内容,希望文章能够帮你解决python – 正确使用os.path和os.join所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶