Pregunta

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)
¿Fue útil?

Solución

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

Otros consejos

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('.')
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top