Dir Command In Python REPL

Pavol Kutaj
Jul 16, 2021

--

The aim of this explainerđź’ˇ is to demonstrate how to use dir in python, i.e. how to navigate through the file structure within REPL/Code.

1. steps

  • import os
  • from pprint import pprint as pp
  • pp(next(os.walk("."))) to return contents of the current workind directory
  • for only files pp(next(os.walk(".")[2]))
  • for only folders pp(next(os.walk(".")[1]))
  • for only path pp(next(os.walk(".")[0]))

2. explanation

  • os.walk(directory) returns a generator that yields a 3-tuple with:
  • dirName
  • list of subdirs
  • list of files
  • to evaluate (get results immediatelly), nest it into the next()

3. sources

--

--

No responses yet