How To List Only Directories In Python
How To List Only Directories In Python
to list only directories in python we use python os module.
import os p=os.listdir(r'C:\Users\enaknar\Desktop\pycharm') for i in p: if os.path.isdir(i): print(i)
Here we are using two functions os.listdir() and os.path.isdir().
os.listdir(): os.listdir() will list all files and directories.
os.path.isdir(): os.path.isdir() will return true or false depends on file or directory. if it is a file it will return false. if it is a directory it will return true.
so here we are storing all files and directories of a given path in a variable called p. and using for and if loop we are checking each item, is file or directory. if it is a file print the file name.
Output:
.idea dfs venv __pycache__ Process finished with exit code 0
- List Only Directories In Python
- python list only directories
- python print only directories.
- print Only Directories In Python
- how to list only directories in python
The code is wrong i represent the name of the folders but not the pathway