How to Get the Absolute File Path in Python

09/11/2021

Contents

In this article, you will learn how to get the absolute file path in Python.

Get the Absolute File Path

You can use the os module in Python to get the absolute file path of a file. Here is an example that demonstrates how to do this:

import os

# Get the absolute file path
file_path = os.path.abspath("file.txt")
print(file_path)

In this example, os.path.abspath is used to get the absolute file path of a file named “file.txt”. The function takes the file name as an argument and returns the absolute file path. Note that the file must exist in the same directory as the Python script or you need to specify the complete path to the file.

The os module in Python provides a way to interact with the operating system. The os.path module specifically provides functions for working with file paths, such as getting the absolute file path, checking if a file exists, and more.

Here are some other useful functions in os.path that you might find useful:

  • os.path.exists(path): Returns True if the specified path exists, False otherwise.
  • os.path.isfile(path): Returns True if the specified path is a file, False otherwise.
  • os.path.isdir(path): Returns True if the specified path is a directory, False otherwise.
  • os.path.join(path1, path2, ...): Joins multiple paths together using the appropriate separator for the operating system. For example, on Windows it would use “\” as the separator, while on Unix-based systems it would use “/”.

Here’s an example that demonstrates how you might use some of these functions:

import os

file_path = "file.txt"

# Check if the file exists
if os.path.exists(file_path):
    # Check if the file is a regular file
    if os.path.isfile(file_path):
        # Get the absolute file path
        abs_file_path = os.path.abspath(file_path)
        print(f"The absolute file path is: {abs_file_path}")
    else:
        print(f"{file_path} is not a file.")
else:
    print(f"{file_path} does not exist.")

This example checks if a file named file.txt exists, and if it does, it checks if it’s a regular file. If it is, it gets the absolute file path and prints it. If the file does not exist, or if it’s not a regular file, an appropriate error message is printed.