Skip to content
Fix Code Error

Getting a list of all subdirectories in the current directory

March 13, 2021 by Code Error
Posted By: Anonymous

Is there a way to return a list of all the subdirectories in the current directory in Python?

I know you can do this with files, but I need to get the list of directories instead.

Solution

Do you mean immediate subdirectories, or every directory right down the tree?

Either way, you could use os.walk to do this:

os.walk(directory)

will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so

[x[0] for x in os.walk(directory)]

should give you all of the subdirectories, recursively.

Note that the second entry in the tuple is the list of child directories of the entry in the first position, so you could use this instead, but it’s not likely to save you much.

However, you could use it just to give you the immediate child directories:

next(os.walk('.'))[1]

Or see the other solutions already posted, using os.listdir and os.path.isdir, including those at “How to get all of the immediate subdirectories in Python“.

Answered By: Anonymous

Related Articles

  • Can't install via pip because of egg_info error
  • In practice, what are the main uses for the new…
  • insert tables in dataframe with years from 2000 to…
  • Ukkonen's suffix tree algorithm in plain English
  • How do I ignore files in Subversion?
  • Simulating a system of resource with…
  • What's the difference between eval, exec, and compile?
  • Checkout another branch when there are uncommitted…
  • How to make the script wait/sleep in a simple way in unity
  • Pros/cons of using redux-saga with ES6 generators vs…
  • What does the "yield" keyword do?
  • Interrupt an earlier timeout event in Simpy
  • Calculate the mean by group
  • Oracle: If Table Exists
  • Python File Error: unpack requires a buffer of 16 bytes
  • How to remember things when it comes to mixture of…
  • ExpressJS How to structure an application?
  • Improved way to get subsets of a list
  • How do I merge two dictionaries in a single…
  • How to update Python?
  • how to list all sub directories in a directory
  • What does Ruby have that Python doesn't, and vice versa?
  • Usage of __slots__?
  • Ember.run.debounce with immediate argument does not…
  • Install pip in docker
  • How to git reset --hard a subdirectory?
  • Reference — What does this symbol mean in PHP?
  • Relative imports for the billionth time
  • Logging best practices
  • What is the difference between bottom-up and top-down?
  • How to correct "TypeError: 'NoneType' object is not…
  • Detach (move) subdirectory into separate Git repository
  • What is a NullReferenceException, and how do I fix it?
  • What are the recommendations for html tag?
  • In plain English, what does "git reset" do?
  • OpenIddict Roles/Policy returns 403 Forbidden
  • How can we deal with a data model containing child…
  • Polymer 2 dynamically merging templates
  • Smart way to truncate long strings
  • What does this symbol mean in JavaScript?
  • Reading a huge .csv file
  • File to import not found or unreadable: compass
  • What is the yield keyword used for in C#?
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Cannot Deserialize JSON String in C#
  • Haskell: ternary tree average, with nested `where`
  • Understanding generators in Python
  • React redux saga - using race has no effect at all
  • how to access parent component scope from a child…
  • Laravel 8 - Eloquent Relationship cannot access…
  • Nested routes in Ember JS and Ember Rails
  • What is the reason for the error message "System…
  • Aurelia UX showcase app fails to load
  • Looking for a good Python Tree data structure
  • How do you clear the SQL Server transaction log?
  • How to use glob() to find files recursively?
  • How to implement a basic iterative pushdown…
  • How can I search sub-folders using glob.glob module?
  • How to group by sequence of tags?
  • Uncaught TypeError: Cannot set property Tree of #…
  • What is the most efficient/elegant way to parse a…
  • How do I modify fields inside the new PostgreSQL…
  • SQL query return data from multiple tables
  • Pandas / Python - Compare numerically each row with…
  • What are type hints in Python 3.5?
  • List Directories and get the name of the Directory
  • What's the difference between HEAD^ and HEAD~ in Git?
  • TypeError: 'tuple' object is not callable when…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • How do I keep only the first map and when the game…
  • The best way to calculate the height in a binary…
  • Error message "Forbidden You don't have permission…
  • How can I manually compile a svelte component down…
  • How to get all files under a specific directory in MATLAB?
  • Properly closing views in Marionette
  • How to avoid exhaustive matching and directly return…
  • How is Perl's @INC constructed? (aka What are all…
  • Keras Sequential API is replacing every layer with…
  • How to track untracked content?
  • Getting Bad Request 400 when sending data to django…
  • What is "entropy and information gain"?
  • How to dispatch a Redux action with a timeout?
  • Difference between "Complete binary tree", "strict…
  • Why the value of input file missing when I input the…
  • How to apply rolling t.test with pandas?
  • Recursively list files in Java
  • What does a "Cannot find symbol" or "Cannot resolve…
  • What does "Could not find or load main class" mean?
  • How to use Boost in Visual Studio 2010
  • Start redis-server with config file
  • Reference - What does this regex mean?
  • yield in component that is called from an each helper
  • How can I find the product GUID of an installed MSI setup?
  • Are dictionaries ordered in Python 3.6+?
  • What is your most productive shortcut with Vim?
  • How to set up file permissions for Laravel?
  • Converting a BST to an array
  • How to get all of the immediate subdirectories in Python
  • How to type multiple yield generator (redux-saga)
  • Obtain most recent value for based on index in a…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Tab key == 4 spaces and auto-indent after curly braces in Vim

Next Post:

Convert a list to a data frame

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error