How to get an absolute file path in Python

543    Asked by IsaacRoss in Python , Asked on Apr 3, 2021

Given a path such as "mydir/myfile.txt", how do I find the file's absolute path relative to the current working directory in Python? E.g. on Windows, I might end up with:

   "C:/example/cwd/mydir/myfile.txt"

Answered by Isaac Ross

There are multiple ways to get absolute path python some are as follows:-

You can import the os library to use the method os.path.abspath() and paste the directory/file name.

 import os

 os.path.abspath("mydir/myfile.txt")

You can use library pathlib to get an absolute path in Python :

from pathlib import Path

p = Path("pythonw.exe").resolve() 
str(p)

Your Answer

Interviews

Parent Categories