Python os.path.abspath() Method

Musfirah Waseem Jan 30, 2023
  1. Syntax of the Python os.path.abspath() Method
  2. Example Codes: The os.path.abspath() Method
  3. Example Codes: Change Current Directory and the os.path.abspath() Method
  4. Example Codes: Use the os.path.dirname() Method With the os.path.abspath() Method
  5. Example Codes: Set Path Address as Empty in the os.path.abspath() Method
Python os.path.abspath() Method

Python os.path.abspath() method tells us an absolute path. The full path starts from the root of the operating file system up until the working directory.

Syntax of the Python os.path.abspath() Method

os.path.abspath(path address)

Parameters

path address It is an address object of a file system path. The object can either be an str or bytes.

Return

The return type of this method is a path string containing the absolute address of a file.

Example Codes: The os.path.abspath() Method

import os

directory = "fileName.txt"

print(os.path.abspath(directory))

Output:

/home/fileName.txt

os.path.abspath() is a simple method to interact with the operating system and retrieve the entire path name of any specific file.

Example Codes: Change Current Directory and the os.path.abspath() Method

import os

directory = "fileName.txt"

os.chdir("/home/Documents/")

print(os.path.abspath(directory))

Output:

/home/Documents/fileName.txt

The os.path.abspath() method removes things like . and / from the path and returns an absolute path from the root of the directory to the current file.

Example Codes: Use the os.path.dirname() Method With the os.path.abspath() Method

import os

directory1 = os.path.abspath(os.path.dirname("fileName.txt"))
directory2 = os.path.dirname(os.path.abspath("fileName.txt"))

print(directory1)
print(directory2)

Output:

/home
/home

The os.path.abspath() method finds the full path of the file in use instead of hardcoding it. This method provides the flexibility to find files or folders and return the correct path on different operating systems.

Example Codes: Set Path Address as Empty in the os.path.abspath() Method

import os

address = ""

directory = os.path.abspath(address)

print(directory)

Output:

/home

os.path.split() returns a complete valid pathname even if enter a partial or empty path address.

Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

Related Article - Python OS