w3resource

Python: Get an absolute file path

Python Basic: Exercise-63 with Solution

Write a Python program to get an absolute file path.

Sample Solution-1:

Python Code:

def absolute_file_path(path_fname):
        import os
        return os.path.abspath('path_fname')        
print("Absolute file path: ",absolute_file_path("test.txt"))

Sample Output:

Absolute file path:  /home/students/path_fname 

Flowchart:

Flowchart: Get an absolute file path.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Sample Solution-2:

Python Code:

from pathlib import Path
p = Path("main.py").resolve()
print(p)

Sample Output:

/tmp/sessions/9f576d81597fd882/main.py

Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]