0

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)
Bob
  • 539
  • 2
  • 5
  • 11
  • Please don't format your code like that, copy and paste it here, highlight it, then presse CTRL-K – jamylak May 31 '13 at 03:37
  • @jamylak yeah sorry, I was in a hurry and this was my first time posting anything. Thanks! – Bob May 31 '13 at 03:41
  • What is wrong with that code? – Cody Guldner May 31 '13 at 03:54
  • @CodyGuldner I put the code into the submission box and just indented using HTML code so it would be a little bit funky but there's nothing wrong with the formatting now – Bob May 31 '13 at 03:55
  • No, I meant that you aren't really asking a question here – Cody Guldner May 31 '13 at 03:56
  • Oh sorry, here's the exact question that I was given: Write a recursive function traverse() that takes as parameters a pathname of a folder as a string and an integer d and prints to the screen the pathname of every file and subfolder contained in the folder, directly or indirectly. The file and subfolder path names should be output with an indentation that is proportional to their depth with respect to the topmost folder. – Bob May 31 '13 at 03:58
  • what is the purpose of `item` in the `for loop`? I see you just assign it a path string but not use it? – Tanky Woo May 31 '13 at 05:30

2 Answers2

1

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))
Seth
  • 45,033
  • 10
  • 85
  • 120
  • that's what I needed thanks. But what's the difference between using os.walk and os.listdr? I'm a novice to python and recursion is giving me a tough time – Bob May 31 '13 at 03:54
  • `os.walk` will recursively look through a directory tree. `os.listdir` just gives you a list of files, without going deeper in to sub folders. – Seth May 31 '13 at 22:15
0

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('.')
Tanky Woo
  • 4,906
  • 9
  • 44
  • 75