-2

I have tried os.listdir() but it shows all the files & directories. I've tried other solutions but they mostly require a loop and I am finding ways to do it without a loop.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Someone
  • 126
  • 8

2 Answers2

1

Use os.walk

import os
subdirs = next(os.walk('.'))[1]
print(subdirs)
Sid
  • 2,174
  • 1
  • 13
  • 29
0

Works with me:

import os

os.mkdir('f')
os.mkdir(r'f/file1')
os.mkdir(r'f/file2')
os.mkdir(r'f/file3')

os.mkdir('f/file1/abc')
os.mkdir('f/file2/def')
os.mkdir('f/file3/ghi')

os.listdir('f')

OT:

['file2', 'file3', 'file1']

listdir with a file

os.listdir('f/file1')

OT:

['abc']
AdrianSK
  • 55
  • 5