root,dir,file的循环是os.walk(startdir)
通过这些步骤工作的吗?
for root in os.walk(startdir)
for dir in root
for files in dir
对?或者它首先得到所有的根,然后所有的dirs第二和所有文件第三?
发布于 2019-03-08 14:03:32
简单来说,os.walk()将生成路径,文件夹,文件存在于给定路径中的元组,并将继续遍历子文件夹。
import os.path
path=input(" enter the path\n")
for path,subdir,files in os.walk(path):
for name in subdir:
print os.path.join(path,name) # will print path of directories
for name in files:
print os.path.join(path,name) # will print path of files
这将生成子目录中所有子目录,文件和文件的路径
发布于 2019-03-08 15:09:56
这是一个简短的例子,说明os.walk()如何使用一些os函数进行一些解释。
首先请注意,os.walk()返回三个项目,根目录,dirs
当前根目录下方的目录列表()以及在这些目录中找到的文件列表。该文档将为您提供更多信息。
dirs
将包含根目录下方的目录列表,文件将包含在这些目录中找到的所有文件的列表。在下一次迭代中,前一个dirs
列表中每个目录的每个目录将root
依次承担角色,搜索将从那里继续,只有在搜索到当前级别后才会进入某个级别。
代码示例:这将搜索,计算和打印指定搜索目录(您的根)下面的文件名.jpg
和.gif
文件。这也使得使用的os.path.splitext()函数从它的延伸和文件的基础分开os.path.join()函数来给你的全名,包括找到的图像文件的路径。
import os
searchdir = r'C:\your_root_dir' # your search starts in this directory (your root)
count = 0
for root, dirs, files in os.walk(searchdir):
for name in files:
(base, ext) = os.path.splitext(name) # split base and extension
if ext in ('.jpg', '.gif'): # check the extension
count += 1
full_name = os.path.join(root, name) # create full path
print(full_name)
print('\ntotal number of .jpg and .gif files found: %d' % count)
https://stackoverflow.com/questions/-100001407
复制相似问题