Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - list all directories/files and follow

Tags:

python

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?

like image 864
Ricky Barnett Avatar asked Feb 02 '26 16:02

Ricky Barnett


1 Answers

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]))
like image 88
Benjamin Hodgson Avatar answered Feb 05 '26 06:02

Benjamin Hodgson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!