本文介绍了我理解 os.walk 对吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

os.walk(startdir) 中的 root、dir、file 循环是通过这些步骤工作的吗?

The loop for root, dir, file in os.walk(startdir) works through these steps?

for root in os.walk(startdir)
    for dir in root
        for files in dir
  1. 获取启动目录的根目录:C:dir1dir2startdir

  1. get root of start dir : C:dir1dir2startdir

获取 C:dir1dir2startdir 中的文件夹并返回文件夹列表dirlist"

get folders in C:dir1dir2startdir and return list of folders "dirlist"

获取第一个目录列表项中的文件并返回文件列表filelist"作为文件列表列表的第一项.

get files in the first dirlist item and return the list of files "filelist" as the first item of a list of filelists.

移动到目录列表中的第二项并返回此文件夹中的文件列表filelist2";作为文件列表列表的第二项.等

move to the second item in dirlist and return the list of files in this folder "filelist2" as the second item of a list of filelists. etc.

移动到文件夹树中的下一个根目录,然后从 2 开始.等

move to the next root in the folder tree and start from 2. etc.

对吧?还是先获取所有根目录,然后获取所有目录,然后获取所有文件?

Right? Or does it just get all roots first, then all dirs second, and all files third?

推荐答案

os.walk 返回一个生成器,该生成器创建一组值(current_path、current_path 中的目录、current_path 中的文件).

os.walk returns a generator, that creates a tuple of values (current_path, directories in current_path, files in current_path).

每次调用生成器时,它都会递归地跟踪每个目录,直到调用 walk 的初始目录中没有其他子目录可用为止.

Every time the generator is called it will follow each directory recursively until no further sub-directories are available from the initial directory that walk was called upon.

因此,

os.walk('C:dir1dir2startdir').next()[0] # returns 'C:dir1dir2startdir'
os.walk('C:dir1dir2startdir').next()[1] # returns all the dirs in 'C:dir1dir2startdir'
os.walk('C:dir1dir2startdir').next()[2] # returns all the files in 'C:dir1dir2startdir'

所以

import os.path
....
for path, directories, files in os.walk('C:dir1dir2startdir'):
     if file in files:
          print('found %s' % os.path.join(path, file))

或者这个

def search_file(directory = None, file = None):
    assert os.path.isdir(directory)
    for cur_path, directories, files in os.walk(directory):
        if file in files:
            return os.path.join(directory, cur_path, file)
    return None

或者如果你想查找文件,你可以这样做:

or if you want to look for file you can do this:

import os
def search_file(directory = None, file = None):
    assert os.path.isdir(directory)
    current_path, directories, files = os.walk(directory).next()
    if file in files:
        return os.path.join(directory, file)
    elif directories == '':
        return None
    else:
        for new_directory in directories:
            result = search_file(directory = os.path.join(directory, new_directory), file = file)
            if result:
                return result
        return None

这篇关于我理解 os.walk 对吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 17:34