How to get an absolute file path in Python


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:

12/27/2018 8:42:24 PM

Accepted Answer

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

Also works if it is already an absolute path:

>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
5/24/2017 10:23:56 PM

You could use the new Python 3.4 library pathlib. (You can also get it for Python 2.6 or 2.7 using pip install pathlib.) The authors wrote: "The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them."

To get an absolute path in Windows:

>>> from pathlib import Path
>>> p = Path("pythonw.exe").resolve()
>>> p
>>> str(p)

Or on UNIX:

>>> from pathlib import Path
>>> p = Path("python3.4").resolve()
>>> p
>>> str(p)

Docs are here:

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow