简体   繁体   English

使用os.walk的递归列表

[英]Recursive list using os.walk

I'm trying to build a list of path names. 我正在尝试建立路径名列表。 The code I have so far is : 到目前为止,我的代码是:

os.chdir(inputDir)

if Resursive is False:
    filePathList = [os.path.join(inputDir, f) for f in os.listdir(inputDir) if f.endswith('.tif')]

if Resursive is True:
    for root, dirs, files in os.walk(inputDir):
        for file in files:
            if file.endswith('.tif'):
                filePathList = (os.path.join(root, file))

Obviously this causes a problem where in the Recursive is True case the filePathList gets overwritten each time. 显然,这会导致问题,在“ Recursive is True情况下,每次都会覆盖filePathList In other languages I'd do something like filePathList[i] = (os.path.join(root, file)) but using walk file and files aren't numbers that can be used as index values. 在其他语言中,我会做类似filePathList[i] = (os.path.join(root, file))但是使用walk filefiles不是可用作索引值的数字。

What's the best way to handle in the Recursive is True case? Recursive is True情况下处理的最佳方法Recursive is True什么?

os.chdir(inputDir)

if Resursive is False:
    filePathList = [os.path.join(inputDir, f) for f in os.listdir(inputDir) if f.endswith('.tif')]

if Resursive is True:
    filePathList = []
    for root, dirs, files in os.walk(inputDir):
        for file in files:
            if file.endswith('.tif'):
                filePathList.append(os.path.join(root, file))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM