您的两个提示都带来了现在看起来像这样的最终解决方案:
def walkThroughPath(self , sBasePath, blFolders = True, blFiles = True, blFollowSymlinks = True ):
aPaths = []
for sRootDir, aSubFolders, aFiles in os.walk( sBasePath, blFollowSymlinks ):
for sFolder in aSubFolders:
if blFolders == True:
try:
aPaths.index( sRootDir )
blPathExists = True
except:
blPathExists = False
pass
if blPathExists == False:
aPaths.append( sRootDir )
self.logDebug("Append: " + sRootDir )
self.logDebug("Current content of aPaths: \n" + pprint.pformat(aPaths) )
for sFileName in aFiles:
self.logDebug("Current root dir: " + sRootDir )
if blFiles == True:
try:
aPaths.index( sRootDir + "/" + sFileName )
blPathExists = True
except:
blPathExists = False
pass
if blPathExists == False:
aPaths.append( sRootDir + "/" + sFileName )
if blFolders == True:
try:
aPaths.index( sRootDir )
blPathExists = True
except:
blPathExists = False
pass
if blPathExists == False:
aPaths.append( sRootDir )
self.logDebug("Append: " + sRootDir )
self.logDebug("Current content of aPaths: \n" + pprint.pformat(aPaths) )
self.logDebug("Folders: " + str(blFolders) )
self.logDebug("Files : " + str(blFiles) )
self.logDebug("Paths found in " + sBasePath + " : \n" + pprint.pformat(aPaths) )
return aPaths
首先,正如史蒂文所说,我缩进不正确。
os.walk 似乎不像我预期的那样处理列表。文件的文件夹不一定会出现在文件夹列表中。这导致我遗漏了许多文件夹,因为这些文件夹路径已在文件列表中。此外,我只检查了这个有限文件夹列表中的文件。
接下来,我按照 unutbu 的建议添加了可选的跟随符号链接标志。也许在我的情况下,最终也可能需要它们。
上面的那些方法肯定是一个改进的候选者,但它至少是有效的:-)
最好的,
安德烈