There is a directory that contains folders as well as files of different formats.
import os
my_list = os.listdir('My_directory')
will return full content of files and folders names. I can use, for example, endswith('.txt')
method to select just text files names, but how to get list of just folders names?
Hover the cursor on the 'From File' option and click on 'From Folder'. In the Folder dialog box, enter the folder path, or use the browse button to locate it. Click OK. In the dialog box that opens, you'll see the names of all the files along with other metadata.
Substitute dir /A:D. /B /S > FolderList. txt to produce a list of all folders and all subfolders of the directory. WARNING: This can take a while if you have a large directory.
os.walk
already splits files and folders up into different lists, and works recursively:
for root,dirs,_ in os.walk('.'):
for d in dirs:
print os.path.join(root,d)
I usually check for directories, while assembling a list in one go. Assuming that there is a directory called foo
, that I would like to check for sub-directories:
import os
output = [dI for dI in os.listdir('foo') if os.path.isdir(os.path.join('foo',dI))]
You can use os.walk()
in various ways
(1) to get the relative paths of subdirectories. Note that '.'
is the same value you get from os.getcwd()
for i,j,y in os.walk('.'):
print(i)
(2) to get the full paths of subdirectories
for root, dirs, files in os.walk('path'):
print(root)
(3) to get a list of subdirectories folder names
dir_list = []
for root, dirs, files in os.walk(path):
dir_list.extend(dirs)
print(dir_list)
(4) Another way is glob
module (see this answer)
Just use os.path.isdir
on the results returned by os.listdir
, as in:
def listdirs(path):
return [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]
That should work :
my_dirs = [d for d in os.listdir('My_directory') if os.path.isdir(os.path.join('My_directory', d))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With