Python: Get an absolute file path
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_fnameclass="p-flowchart">Flowchart:
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
Python Code Editor:
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 Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics