F.E. PPS Unit 4 Practical 10 solution

Practical 10: Program to print the absolute path of a file using the os.path.join function.

Problem Statement

Write a Python program to print the absolute path of a file using the os.path.join function.

Solution Code

				
					import os

# Function to get absolute path of a file
def get_absolute_path(filename):
    # Get the current working directory
    current_directory = os.getcwd()

    # Join the directory path with the filename
    absolute_path = os.path.join(current_directory, filename)

    # Print the absolute path
    print(f"Absolute Path of '{filename}': {absolute_path}")

# Example: Provide a filename
get_absolute_path("sample.txt")

				
			

Output

When the program is executed, it should display the absolute path of the file sample.txt (or any provided filename) based on the current working directory.

Example Output

				
					Absolute Path of 'sample.txt': D:\python\sample.txt
Process finished with exit code 0
				
			

If the program runs in a different directory, the output will reflect the correct absolute path.

Explanation

Below is the explanation of F.E. PPS Unit 4 Practical 10 solution where we have written Python program to print the absolute path of a file using the os.path.join function.

  1. Getting the Current Directory (os.getcwd())
    • The program first gets the current working directory.
  2. Joining the Directory Path with the Filename (os.path.join())
    • os.path.join(current_directory, filename) constructs the absolute path by appending the filename to the current directory.
  3. Printing the Absolute Path
    • The absolute path of the file is displayed as output.

Key Concepts Learned

  • Working with File Paths (os.path module)
    • os.getcwd() → Retrieves the current working directory.
    • os.path.join(directory, filename) → Joins a directory path with a filename to create a full path.
  • Portability
    • Using os.path.join() ensures compatibility across different operating systems (Windows, macOS, Linux).
Tech Amplifier Final Logo