Find the path to the given file in Python

Python users frequently work with files, particularly when reading, writing, or modifying data. However, finding a file's path is essential before performing any file operations. A file path refers to the location or directory where the file is stored in the system.

Python provides several methods to find file paths ?

  • Pathlib Module Modern, object-oriented approach

  • OS Module Traditional method using os.path.abspath()

  • os.path.join() method Combines path components

  • os.getcwd() method Gets current working directory

Using the Pathlib Module

The pathlib module provides a modern, object-oriented approach to handle file paths. The absolute() method returns the complete path from the root directory.

Example

from pathlib import Path

# Create a Path object for the file
file_path = Path("sample.txt")
absolute_path = file_path.absolute()
print("Absolute path:", absolute_path)

The output of the above code is ?

Absolute path: /home/user/sample.txt

Using the OS Module

The os.path.abspath() function takes a filename or relative path and returns the absolute path as a string.

Example

import os

file_name = "sample.txt"
abs_path = os.path.abspath(file_name)
print("Absolute path:", abs_path)

The output of the above code is ?

Absolute path: /home/user/sample.txt

Using os.path.join() Method

The os.path.join() method combines multiple path components into a single complete path, making it platform-independent.

Example

import os

# Join multiple path components
base_path = "/home"
file_path = os.path.join(base_path, "user", "documents", "sample.txt")
print("Joined path:", file_path)

The output of the above code is ?

Joined path: /home/user/documents/sample.txt

Using os.getcwd() Method

The os.getcwd() method returns the current working directory. You can combine it with a filename to get the complete path.

Example

import os

# Get current working directory
current_directory = os.getcwd()
print("Current directory:", current_directory)

# Join with filename
file_name = "sample.txt"
full_path = os.path.join(current_directory, file_name)
print("Full path:", full_path)

The output of the above code is ?

Current directory: /home/user
Full path: /home/user/sample.txt

Comparison

Method Best For Returns
pathlib.Path() Modern Python (3.4+) Path object
os.path.abspath() Traditional approach String
os.path.join() Building paths from parts String
os.getcwd() Files in current directory String

Conclusion

Use pathlib for modern Python applications as it's more readable and powerful. Use os.path methods for compatibility with older Python versions. All methods work cross-platform and handle different operating system path conventions automatically.

Updated on: 2026-03-27T13:20:02+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements