GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • w3resource
  • Front End
  • HTML
  • CSS
  • JavaScript
  • HTML5
  • Schema.org
  • php.js
  • Twitter Bootstrap
  • Responsive Web Design tutorial
  • Zurb Foundation 3 tutorials
  • Pure CSS
  • HTML5 Canvas
  • JavaScript Course

This view

  • Original page
  • New address

GeezerVison is showing www.w3resource.com — Python: Get an absolute file path - w3resource

Python: Get an absolute file path

Last update on May 17 2025 05:43:25 (UTC/GMT +8 hours)


Absolute File Path Finder

Write a Python program to get an absolute file path.

Sample Solution-1:

Python Code:

# Define a function named absolute_file_path that takes a parameter 'path_fname'.
def absolute_file_path(path_fname):
    # Import the 'os' module for working with file paths and directories.
    import os
    
    # Use 'os.path.abspath()' to get the absolute file path by providing 'path_fname'.
    return os.path.abspath(path_fname)

# Call the function and print the result, passing "test.txt" as the argument.
print("Absolute file path: ", absolute_file_path("test.txt"))

Sample Output:

Absolute file path:  /home/students/path_fname 
class="p-flowchart">Flowchart:

Flowchart: Get an absolute file path.


Sample Solution-2:

Python Code:

# Import the 'Path' class from the 'pathlib' module, which provides an object-oriented interface to file system paths.
from pathlib import Path

# Create a Path object 'p' by providing the file path "main.py" and resolving it to its absolute path.
p = Path("main.py").resolve()

# Print the absolute path of the file.
print(p)

Sample Output:

/tmp/sessions/9f576d81597fd882/main.py

For more Practice: Solve these Related Problems:

  • Write a Python program to get the absolute path of a given relative path.
  • Write a Python program to check if a given absolute path exists in the system.
  • Write a Python program to extract the directory name from an absolute file path.
  • Write a Python program to normalize a given file path by resolving redundant separators.

Go to:

  • Python Basic Exercises Home ↩
  • Python Exercises Home ↩

Previous: Write a Python program to convert all units of time into seconds.
Next: Write a Python program to get file creation and modification date/times.

Python Code Editor:

 

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.


  • Daily Coding Challenges & Projects
  • Weekly Trends and Language Statistics



You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.