0

The below snippet returns all the folders and it's sub-directories

for r, d, f in os.walk('/tmp/'):
    for folder in d:
        print folder

What I need is only the folders inside the current folder /tmp/

Version: Python 2.7

Prashanth Sams
  • 19,677
  • 20
  • 102
  • 125

1 Answers1

0

os.walk('/tmp/').next()[1] lists all the folders inside the current directory

for folder in os.walk('/tmp/').next()[1]:
    print folder
Prashanth Sams
  • 19,677
  • 20
  • 102
  • 125
  • Or `next(os.walk('/tmp/'))[1]`. Usually, you should prefer letting the `next` function call the method for you, rather than invoking the method explicitly. – chepner Feb 27 '20 at 16:43
  • If nothing else, it's one less thing you'll have to change when making the code work with Python 3 (since the `next` method was renamed `__next__`, but the function kept the same name). – chepner Feb 27 '20 at 16:51