Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

"C:/example/cwd/mydir/myfile.txt" 
like image 364
izb Avatar asked Sep 09 '08 10:09

izb


People also ask

What is an absolute path in Python?

Python: Absolute Path vs. Relative Path. An absolute path is a path that describes the location of a file or folder regardless of the current working directory; in fact, it is relative to the root directory. A relative path that depicts the location of a file or folder is relative to the current working directory.

How do I find the absolute path of a file?

You can determine the absolute path of any file in Windows by right-clicking a file and then clicking Properties. In the file properties first look at the "Location:" which is the path to the file. In the picture below, the location is "c:\odesk\computer_hope".

How do I find the relative path of a file in Python?

path. relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory. Note: This method only computes the relative path.


2 Answers

>>> import os >>> os.path.abspath("mydir/myfile.txt") 'C:/example/cwd/mydir/myfile.txt' 

Also works if it is already an absolute path:

>>> import os >>> os.path.abspath("C:/example/cwd/mydir/myfile.txt") 'C:/example/cwd/mydir/myfile.txt' 
like image 192
sherbang Avatar answered Sep 30 '22 03:09

sherbang


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 WindowsPath('C:/Python27/pythonw.exe') >>> str(p) 'C:\\Python27\\pythonw.exe' 

Or on UNIX:

>>> from pathlib import Path >>> p = Path("python3.4").resolve() >>> p PosixPath('/opt/python3/bin/python3.4') >>> str(p) '/opt/python3/bin/python3.4' 

Docs are here: https://docs.python.org/3/library/pathlib.html

like image 23
twasbrillig Avatar answered Sep 30 '22 03:09

twasbrillig