Recursive list using 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. 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.


Recursive is True


filePathList


filePathList[i] = (os.path.join(root, file))


walk


file


files



What's the best way to handle in the Recursive is True case?


Recursive is True





Before loop declare a variable filePathList = , In the if condition at last line Try filePathList.append(os.path.join(root, file))
– Surya Tej
Jul 2 at 10:07


filePathList =


filePathList.append(os.path.join(root, file))




1 Answer
1


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))






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

iOS Top Alignment constraint based on screen (superview) height