3

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?

Ricky Barnett
  • 1,130
  • 3
  • 15
  • 32
  • 4
    It seems you need somethink like this: http://stackoverflow.com/a/16974952/2707359 – Ilya Feb 15 '16 at 10:48
  • @Ilya was thinking same thing, though with some serious nesting to iterate over os.walk and then iterate through os.walks filenames to try and make it a one liner. – David Feb 15 '16 at 10:52
  • It doesn't have to be a one liner, I can save into a .py file and execute if required. – Ricky Barnett Feb 15 '16 at 10:56

2 Answers2

3

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]))
Benjamin Hodgson
  • 42,952
  • 15
  • 108
  • 157
1
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.

thavan
  • 2,409
  • 24
  • 32