Python find path to directory

How to get a relative path in Python

When you’re working on a project with multiple people, it could be possible that you’re needing to import files or data from a specific location within the project without writing down the full path.

Therefore you want to find out the path relative to the current working directory where you run your Python code.

A relative path starts with / , ./ or ../ .

To get a relative path in Python you first have to find the location of the working directory where the script or module is stored. Then from that location, you get the relative path to the file want.

What is a relative path in Python?

A relative path in Python is a path that describes the location of a directory relative to the entry point where you run the Python script.

So let’s say you run your Python code in ~/home/projects/example-project/app.py .

This is the entry point where you run the top-level code of your python module and acts as the starting point for the relative path. A relative path usually starts with / , ./ or ../ .

To give a further explanation, let’s look at the files and directories that are in this example-project .

~/home/projects/example-project/ ├── app.py ├── cdk.context.json ├── cdk.json ├── mypy.ini ├── README.md ├── requirements.txt ├── src │ ├── __init__.py │ ├── bin │ │ ├── __init__.py │ │ ├── environments │ │ └── load_dotenv.py │ ├── lib │ │ ├── __init__.py │ │ ├── api │ │ ├── compute │ │ ├── constructs │ │ ├── database │ │ ├── skeleton │ │ └── storage │ └── main.py ├── tests │ ├── __init__.py │ └── test_main.py └── tox.ini

So for example, if you need to access ~/home/projects/example-project/src/lib then the relative path is ./src/lib/ in this Python project.

Using relative paths simplifies the code since you don’t need to write the full absolute path in order to find a file or directory in your Python project.

How to find the relative path in Python

You can run your Python script on different operating systems, therefore you want to automatically find the full path of the file you wish to import into your code instead of hardcoding it. This can be accomplished by combining the absolute path with the relative path in order to get the file or folder in your project.

Читайте также:  Python all variables in object

We’ll use the app.py from the previous example and from this working directory we want to get the ./src/lib relative path.

To get the relative path in Python you write the following code:

import os absolute_path = os.path.dirname(__file__) relative_path = "src/lib" full_path = os.path.join(absolute_path, relative_path)

First, you have to import the os module in Python so you can run operating system functionalities in your code.

Then you create the variable absolute_path which fetches the current directory relative to the root folder. This is the full path to your working directory, in this case, ~/home/projects/example-project/ .

The advantage to getting the absolute path on your operating system is that it makes it possible to run the script on different systems on different working directories.

The relative_path variable is a string in which you define the location of the folder that you want to fetch relative to the working directory. In this case, «src/lib» .

Then we use the absolute_path and combine it via join with the relative_path to get the full path to the lib folder which results in:

/Users/dannysteenman/projects/example-project/src/lib/

Conclusion

As you can see, a relative path can be useful to simplify your code without having to write down the full path to a folder or file in your Python code.

Instead, you only point to the location of a directory relative to your working directory or the entry point of your Python script.

If you need guidance on finding an absolute path in Python, read the following article below.

Источник

How to Find the Current Working Directory in Python

How to Find the Current Working Directory in Python

Learn how to get current directory (or path) in Python using pathlib and os modules

Python provides two different ways to get the current working directory. The first method uses the os module and the second uses the newer pathlib .

Using the os Module to Get the Current Directory

First thing you need to do is to import the module.

Then, you just need call the getcwd function.

>>> import os . >>> os.getcwd() '/home/miguel' 

And that is it! As you can see, the function returns a string. This is not very flexible, what if you want to list all the files in that directory? You will have to call it on os functions again.

The os module is pretty ancient and I wouldn’t recommend using it nowadays. In the following section, I’m going to show you the modern way of getting the current working directory in Python.

Читайте также:  Заменить файл index html

Getting the Current Working Directory Through the pathlib Module

The pathlib module was proposed in 2012 and added to Python in the 3.4 version. The idea was to provide an object-oriented API for filesystem paths. This module provides classes that represent the filesystem paths with semantics appropriate for different operating systems. Also, Path objects are immutable and hashable, which helps prevent programming errors caused by mutability.

To get the current working directory using pathlib you can use the classmethod cwd from the Path class. But first, you need to import it.

Them, you can call the method.

>>> from pathlib import Path . >>> Path.cwd() PosixPath('/home/miguel') 

As you can see, the output is different than the os.getcwd() . As I mentioned earlier, all paths follow the semantics of the underlying filesystem. In my case, I’m using Linux, so the output is a PosixPath . On Windows, cwd returns a WindowsPath .

Being an object allows many cool functionalities such as iterating over all files just by calling a method. However, If you still want to get the string representation, you can call str on the Path.cwd() .

Path.cwd Under the Hood

How does Path know the current directory? The answer is: it calls the os and returns an instance of Path . The following snippet shows the actual implementation.

 @classmethod def cwd(cls): """Return a new path pointing to the current working directory (as returned by os.getcwd()). """ return cls(os.getcwd()) 

Wait! On Linux it returns a PosixPath but the class method belongs to Path . How does it know?

Great question! Path does some magic behind the scenes before creating the object. It implements the __new__ magic method and calls os to determine the underlying operating system. Check the implementation.

 def __new__(cls, *args, **kwargs): if cls is Path: cls = WindowsPath if os.name == 'nt' else PosixPath self = cls._from_parts(args, init=False) if not self._flavour.is_supported: raise NotImplementedError("cannot instantiate %r on your system" % (cls.__name__,)) self._init() return self 

Conclusion

That’s it for today, folks! I hope you enjoyed this brief article.

Источник

How to Get the Current Directory in Python

Programming in Python and need to get the present working (current) directory? Use these commands to find it.

How to Get the Current Directory in Pytthon-Featured

Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.

One of the most important aspects of programming you must understand is your project directory. It gives you a better grasp of your files and lets you relate with them more easily—especially when you need to carry out actions like file linking, module import, directory switching, and much more.

Whether for urgent reasons or future needs, it’s a necessary aspect when executing Python projects as well.

Читайте также:  Подключение скриптов

So let’s highlight the techniques you can use to get your current Python directory, as well as some other possible tweaks you can apply to it generally.

Dealing with Python Directories

The methods that deal with the Python working directory are in its inbuilt os module and are the same for all OSes. Thus, it means you need to import that module before you can start executing commands that deal with your working directory.

However, just like any other Python line or block of code, these commands are written in a Python shell. Or a Python file if you’re using other code editors. And if you’re working from the command line, you need to enter the Python shell by typing python. That’s because the os methods are Python packages, and you can’t execute them directly from the CMD.

Get the Current Python Working Directory

You can get your current Python directory by using either the os.path or os.getcwd method. However, while os.getcwd, which is the more common method, only checks your current working directory, the os.path method can check both the current directory as well as the base path of your working directory.

To get the base path of your Python working directory with the os.path method, write the following within your Python file or shell:

import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(BASE_DIR)

However, to use the above method to check the active working directory, type the following:

import os
CURR_DIR = os.path.dirname(os.path.realpath(__file__))
print(CURR_DIR)

Getting the current Python directory with the os.getcwd method is quite straight forward; to use it, run the following lines in your shell or Python file:

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

Switching Your Current Python Directory

You can change the current Python directory to inherit another file path if you like. To do that, you only need to define the file path for the new working directory as done in the code snippet below. Ensure that you replace the path with the one that applies to you:

import os
chd = os.chdir('C:/Users/Omisola Idowu/Desktop/my_project')
CURR_DIR = os.getcwd()
print(CURR_DIR)

The code above changes the current working directory to the one in parenthesis. Thus, the output of the snippet above returns the full path of the new directory you entered in the os.chdir() method.

Other Tweaks for Dealing with Python Directories

Beyond getting the current directory, there are other things you can do to deal with Python working paths. You can list the files and sub-folders within a Python working directory, as well as rename, remove, or make a Python directory by writing either of the following lines in your Python shell.

Источник

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