Question

I'm trying to print the pathnames of every file and its subfolders in a folder
This is the code I have so far:

def traverse(path, d):
    for item in os.listdir(path):
        item = os.path.join(path, d)
        try:
            traverse(path,d)
        except:
            print(path)
Was it helpful?

Solution

You're looking for os.walk.

You can use it something like:

def traverse(path):
    for root, dirs, files in os.walk(path):
        print(root)

        # if you want files too: 
        for f in files: 
            print(os.path.join(root, f))

OTHER TIPS

I don't know what is the purpose of this statement:

item = os.path.join(path, d)

I write the code as I understanding:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os

def traverse(path):
    for item in os.listdir(path):
        newpath = os.path.join(path, item)
        if os.path.isdir(newpath):
            traverse(newpath)
        else:
            print newpath

if __name__ == '__main__':
    traverse('.')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top