How to get current directory in python

How to get current directory name in Python

In this Python tutorial, I will explain to you, how to get current directory name in Python. By using the Python os module, we will see, how to get current folder name in Python.

Python os module

Before we start, it is essential to understand the ‘os’ module. Python’s os module provides functions to interact with the operating system. This module comes in handy when we want to work with files and directories. One of the common tasks we can do with this module is to get the current directory name.

Get Current Directory in Python Using os.getcwd()

The getcwd() function of the os module returns the current working directory in Python. Here’s how we can use it to get the current folder in Python.

import os current_directory = os.getcwd() print(current_directory)

When you run this code, it will print the full path of your current working directory.

Читайте также:  HTML

How to get current directory name in Python

To get just the name of the current directory (and not the full path) or the folder name, we can use the os.path.basename() function. Here’s how we can use it:

import os current_directory = os.getcwd() directory_name = os.path.basename(current_directory) print(directory_name)

This code will print the name of the current directory in Python, without the full path. Or this is how to get the folder name in Python.

How to get current directory name in Python example

Get Directory Name Using os.path.dirname()

Another function from the os module that we can use to get the directory name is os.path.dirname() . The dirname() function returns the directory component of a pathname. However, in most cases, if we want to get the current directory, we still have to use it in conjunction with os.getcwd() :

import os current_directory = os.getcwd() print(os.path.dirname(current_directory))

This code will print the directory that contains the current directory, not the current directory itself.

Get current directory name in Python

To get just the name of the current directory (and not the full path), we can use the os.path.basename() function in conjunction with os.path.dirname() :

import os current_directory = os.getcwd() directory_name = os.path.basename(os.path.dirname(current_directory)) print(directory_name)

Get current directory name in Python example

get the current directory name in Python using pathlib

Pathlib is a module in Python used for object-oriented filesystem paths. It was designed to be simple to use and to represent filesystem paths with semantics appropriate for different operating systems. Here’s how to get the current directory using pathlib in Python:

from pathlib import Path # Get current directory current_directory = Path.cwd() print(current_directory)

get the current directory name in Python using pathlib

Just like with the os module, this will print the full path of the current directory. To get just the name of the current directory, we can use the .name attribute:

from pathlib import Path # Get current directory current_directory = Path.cwd() # Get current directory name directory_name = current_directory.name print(directory_name)

get the current directory name in Python using pathlib example

Conclusion

In this Python tutorial, We’ve looked at different methods to get the current directory in Python, using both the os and pathlib modules.

Remember, os.getcwd() and Path.cwd() give you the current working directory as a full path in Python. If you want only the name of the current directory, you can use os.path.basename(os.getcwd()) or Path.cwd().name .

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

How to get the current directory in python?

In this python tutorial, we look at how you can get the current working directory in Python and how you can change the working directory. This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts. However, in case you are here only for the solution use this link.

Table of Content

What are directories and how do they work?

In case you are new to programming, directories are nothing but folders. These directories are present inside a root folder eg: C: \ or D: \ and each directory could contain files or subdirectories and so on. And to retrieve a file from you would need to know the exact path to reach the file, in windows you can view a particular file path by right-clicking the file-General-Location.

Furthermore, when you run a python script, the current directory is set to the location of the script. And, while trying to run another script or while handling files in python the Current Working Directory (CWD) is important as python would not be able to access the files if there aren’t in the CWD. It is in these scenarios that the python get current directory helps you know which directory you are in currently.

Python get current directory

The python get current directory would help you know which directory you are currently in, to do this we use the OS module to interact with the operating system and we use the os.getcwd() method to return the path of the current directory.

Syntax of os.getcwd:

Источник

Discover How to Get the Current Directory in Python

Python get current directory

One of the most powerful features of Python is its ability to provide you with information about the current Directory. This makes it easy to know where everything is in your program at any given time.

To get this information, just type the following command: Python -c “import os; print(os.getcwd())”

Directory

A directory includes a collection of different subdirectories and files that contain content. You can work with the modules mentioned below to work with directories.

Current Working Directory

The current working Directory is a special location in computer files. It contains the path to your Python script. You can use the Python directory() function to get the current working directory of your Python scripts.

Absolute and Relative Paths

An absolute path is one which provides you with the location of a file concerning the root directory.

On the other hand, the relative path takes into account the current Directory. There is no need to specify the root directory location here.

While specifying the relative path, a single dot (.) means the current Directory, while a double dot(..) means parent directory.

Getting Directory in Shell

The process of getting the current working Directory is as follows:

1) Open a new file or create a blank one.

2) Type in your Python code and save it with the .py extension.

3) Run the following command from a command prompt: cwd()

Getting a Directory in Python Program

Sometimes, you might want to check the current Directory in your Python program or get the current working directory for a project or script. Here are some ways to do that. os.getcwd() and os.chdir() are widely known functions to achieve our result.

Using os Module to get the current Directory

Various methods in the os module will help you get the desired results.

1. Using os.getcwd()

getcwd means get a current working directory and it is a part of the os module. Hence, you need to import this module before using the function. This function will provide you with the path of the file. The absolute path is the output in string format.

import os path = os.getcwd() print(path)

2. Using os.chdir()

If you wish to change the Directory, opt for this function. This function has a path as its argument. Hence, you need to specify the new path to transfer your file contents. chdir means change directory.

3. Using os.path

Here, you can get the directory name from the provided path. You need to use the file path as an argument here. Using the file path, the function will provide a directory name.

dir_name = os.path.dirname(filepath) print(dir_name)

4. Get a full path to the Directory

In this method, you can easily remove or get rid of symbolic links ( any shortcuts to directory location.) Output is of string data type.

import os dir_path = os.path.dirname(os.path.realpath(__file__))

Using Path Module to get Current Working Directory

The Path module is the newest addition to the list of methods used to get the current working directory in Python. It will easily provide you with the path of the Directory you’re currently working in.

from pathlib import Path print(Path.cwd())

Working with Mac/Windows

Mac uses forward slash, while Windows uses backslash while specifying paths of directories. With the pathlib functions, go for forward slashes. It will convert into the right format on its own.

Using .absolute() with pathlib

With this function, you will obtain the absolute path of cwd.

import pathlib print(pathlib.Path().absolute()) #this will give the current working directory's absolute path

Using .resolve() with pathlib

Here, you just have to import pathlib and use the resolve() function. Through this,you will obtain the current directory location in Python.

pathlib.Path().resolve() #make sure that you import pathlib at the #beginning of function call

Get the current Directory and join

Supposedly you have a file in the current working directory, and you need to add it to a certain folder, you can use the join() method. For this, get the location of the current Directory using getcwd() and post this, join the current directory path to the desired destination folder path. Observe this example:

import os current = os.getcwd() answer = os.path.join(cwd, "destination/folder")

Python glob get current Directory

glob is a Python module that provides us with a list of files that are situated in a directory. glob is used to match patterns too. Its syntax is as follows:

My_path = os.getcwd()+'\\My_dir\\*' for file_path in glob.glob(My_path): print(file_path) #this gives output as files with the related paths

Python get current Directory in Jupyter

Opt for pwd to check the current working directory in a Jupyter Notebook. os.getcwd() will also fetch the same result using the os module.

If you want to change the current Directory, enter:

and verify using os.getcwd() again. You can check whether the Directory’s location has been changed or not.

Get current venv path

In case you wish to obtain the path of the virtual environment, use the VIRTUAL_ENV. You can apply this only if you have activated the entire setup. Import the os module first and then

print(os.environ['VIRTUAL_ENV'])

Источник

Оцените статью