Get current directory or folder name (without the full path)
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Retrieving the current directory or folder name without including the full path is a common task in programming and scripting. This functionality is essential when there is a need to handle files relative to the current directory or to understand the context within which a program is executing. Different programming languages provide various methods to achieve this, and in this article, we'll explore how this can be done in some popular programming environments.
Understanding Current Directory
Before diving into specific examples, it's important to understand what "current directory" means in different contexts. The current directory, often referred to as the working directory, is the folder in which your program or script is operating. This can change during the execution of a program if the script or program changes the directory explicitly.
Retrieving Current Directory Name in Various Programming Languages
Python
In Python, you can use the os module to work with the filesystem. The os.getcwd() function returns the current working directory string which includes the full path. To extract only the directory name, you can use os.path.basename().
JavaScript (Node.js)
In Node.js, you can use the process.cwd() function to retrieve the current working directory and the path module to manipulate paths.
Bash
In shell scripting with Bash, you can use the pwd command along with basename to get the current folder name.
PowerShell
In PowerShell, similar to other scripting languages, you can use built-in utilities to fetch the current directory and extract the folder name.
Summary Table
Here’s a table summarizing the methods used across different programming environments:
| Language/Tool | Function to Get Current Directory | Function to Extract Folder Name | Combined Code Snippet |
| Python | os.getcwd() | os.path.basename() | os.path.basename(os.getcwd()) |
| Node.js | process.cwd() | path.basename() | path.basename(process.cwd()) |
| Bash | pwd | basename | basename $(pwd) |
| PowerShell | Get-Location | Split-Path -Leaf | Split-Path -Leaf (Get-Location) |
When to Use This Functionality
Knowing the current directory name without the full path can be useful in a variety of scenarios:
- Logging: To log the execution context without revealing full path information for security reasons.
- Configuration: When reading config files relative to the current folder without needing to hard-code paths.
- File Manipulation: To create or manage files relative to the current execution context dynamically.
Understanding how to retrieve the current directory or folder name in different programming environments enhances flexibility and efficiency in software development and system administration.

