Ricky Barnett
Ricky Barnett

Reputation: 1170

Python - list all directories/files and follow

I have the following command I'm running on my remote server

python -c 'import os, json; print json.dumps(os.listdir("."))'

This works fine for listing files/directories in the current directory however how would I change this to follow directories and list the containing files?

Upvotes: 3

Views: 356

Answers (2)

thavan
thavan

Reputation: 2429

out_list = []
for (path, dirs, files) in os.walk("."):
    for f in files:
        out_list.append(os.path.join(path, f))
    for d in dirs:
        out_list.append(os.path.join(path, d))

print json.dumps(out_list)

This will include directories and files in the output with full path.

Upvotes: 1

Benjamin Hodgson
Benjamin Hodgson

Reputation: 44634

Python, ever eager to please, provides a standard library function for that. os.walk wraps up the pattern of recursively listing files in subdirectories.

Here's how you could json-ify a list of all the files in this directory or any subdirectories. I'm using a two-level list comprehension to concatenate the lists of files:

import json
import os

print(json.dumps([file for root, dirs, files in os.walk('.') for file in files]))

Upvotes: 3

Related Questions