Get Absolute Path in Python

Python absolute path

We often use files to store the outputs of our programs in permanent storage. Generally, we work with relative paths of files in our programs. In this article, we will discuss two ways to get the absolute path to a file in python from its relative pathname.

What is an absolute path to a file?

The absolute path to a file is the entire file path from the root file to the current file. For instance, Look at the following image. 

file-path image

You can observe that the sample.txt path is present in the java2blog folder. The java2blog folder is present in the codes folder.

Here, the absolute path of the file sample.txt will always be “/home/aditya1117/codes/java2blog/sample.txt”

On the other hand, its relative path will always change according to the folder from which we are viewing the file.  For instance, 

  • If we are currently in the java2blog folder, the relative path of the file will be /sample.txt.
  • However, If we move to the folder codes, the relative path to the file sample.txt will be /java2blog/sample.txt.

So, the relative path to a file changes according to the folder we are currently in. Whereas, the absolute path to a file never changes until the file is moved to another location. We can access the file using the absolute path from any directory. Whereas, we will have to update the relative path if we move to any other directory even if the file is at the same location.

How to get absolute path in Python

Let us now look at the ways to get the absolute path to a file in python.

Use abspath to get the absolute path to file

The os module in python provides us with the abspath() method under the os.path property. The abspath() method takes the relative path to a file and returns the absolute path in the string format as shown in the following example.

Output:

Here, the sample.txt file is present in the same folder as our source code file. So, the relative file has been given as only the file name.

use pathlib module to get the absolute path to file

Instead of using the os module, we can use the pathlib module to get the absolute path to a file in python. Here, we will use the Path() function and the absolute() method to get the absolute path to a file.

The Path() function takes the file name as input and creates a path object.  We can invoke the absolute() method on the path object to get the absolute path to a given file as follows.

Output:

Conclusion

In this article, we have discussed the relative path and the absolute path to a file. We have also discussed two approaches to get the absolute path in python. You can choose any of the approaches according to your preference as both the approaches have almost the same cost of execution.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 27 December

    Create Array of All NaN Values in Python

    Table of ContentsUsing numpy.empty() FunctionUsing numpy.full() FunctionUsing numpy.tile() FunctionUsing numpy.repeat() FunctionUsing Multiplication of numpy.ones() with nan Using numpy.empty() Function To create an array of all NaN values in Python: Use numpy.empty() to get an array of the given shape. Assign numpy.nan to every array element using the assignment operator (=). [crayon-63b57f0355e57263392640/] [crayon-63b57f0355e5e724987661/] We used numpy.empty() […]

  • 27 December

    Call Function from Another Function in Python

    Table of ContentsCall a Function in PythonCall Function from Another Function in PythonCall a Function from Another Function within the Same/Different Classes Call a Function in Python To call a function in Python: Write a test() function, which prints a message. Call the function defined in the previous step. [crayon-63b57f035653e197204769/] [crayon-63b57f0356544194039388/] To call a function, […]

  • 27 December

    [Fixed] NameError Name ‘unicode’ is Not Defined in Python

    Table of ContentsUse str() MethodUse sys.version_info with strUse six.text_type Use str() Method To resolve the NameError: name 'unicode' is not defined, replace the occurrence of unicode() with str(). This issue occurs because unicode() was renamed to str() in Python 3. [crayon-63b57f0356b9b149942556/] [crayon-63b57f0356ba1971684855/] Unicode is a computing industry standard that ensures that text from most of […]

  • 26 December

    Repeat List N Times in Python

    Table of ContentsUsing the * operatorUsing the numpy.repeat() functionUsing the list comprehension techniqueUsing the itertools.repeat() functionConclusion This tutorial will demonstrate how to repeat list n times in Python. Using the * operator To repeat list n times in Python, use the * operator. Star operator(*) is used to multiply list by number e.g. lst*3 and […]

  • 26 December

    Get First Day of Next Month in Python

    Table of ContentsGet First Day of Next Month in PythonUsing the datetime.replace() with datetime.timedelta() functionUsing the calendar.monthrange() functionUsing the dateutil.relativedelta objectConclusion Get First Day of Next Month in Python This tutorial will demonstrate how to get first day of next month in Python. Using the datetime.replace() with datetime.timedelta() function To get first day of next […]

  • 25 December

    Convert String Array to Int Array in Python

    Table of ContentsUsing the for loop with int() functionUsing for loop with eval() functionUsing the map() with list() functionConclusion This tutorial will demonstrate how to convert string array to int array in Python. Using the for loop with int() function To convert string array to int array in Python: Use the for loop to loop […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.