Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python folder names in the directory

Tags:

python

how can i get the folder names existing in a directory using Python ?

I want to save all the subfolders into a list to work with the names after that but i dont know how to read the subfolder names ?

Thanks for you help

like image 231
HightronicDesign Avatar asked Mar 23 '15 09:03

HightronicDesign


People also ask

How do I show file names in a directory in Python?

Use isfile() function path. isfile('path') function to check whether the current path is a file or directory. If it is a file, then add it to a list. This function returns True if a given path is a file.

How do you name a folder in Python?

Python os. rename() function enable us to rename a file or directory, directly from command prompt or IDE. The os. rename() function alters the name of the source/input/current directory or file to a specified/user-defined name.

How do I read a directory in Python?

os. listdir() method in python is used to get the list of all files and directories in the specified directory. If we don't specify any directory, then list of files and directories in the current working directory will be returned.


1 Answers

You can use os.walk()

# !/usr/bin/python  import os  directory_list = list() for root, dirs, files in os.walk("/path/to/your/dir", topdown=False):     for name in dirs:         directory_list.append(os.path.join(root, name))  print directory_list 

EDIT

If you only want the first level and not actually "walk" through the subdirectories, it is even less code:

import os  root, dirs, files = os.walk("/path/to/your/dir").next() print dirs 

This is not really what os.walk is made for. If you really only want one level of subdirectories, you can also use os.listdir() like Yannik Ammann suggested:

root='/path/to/my/dir' dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item)) ] print dirlist 
like image 71
Christian Eichelmann Avatar answered Oct 09 '22 13:10

Christian Eichelmann