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 in Python? E.g. on Windows, I might end up with:

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


Asked by: Fenton945 | Posted: 24-09-2021






Answer 1

>>> 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'

Answered by: Tara557 | Posted: 25-10-2021



Answer 2

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

Answered by: Brooke292 | Posted: 25-10-2021



Answer 3

import os
os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))

Note that expanduser is necessary (on Unix) in case the given expression for the file (or directory) name and location may contain a leading ~/(the tilde refers to the user's home directory), and expandvars takes care of any other environment variables (like $HOME).

Answered by: Emily204 | Posted: 25-10-2021



Answer 4

Install a third-party path module (found on PyPI), it wraps all the os.path functions and other related functions into methods on an object that can be used wherever strings are used:

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

Answered by: Samantha949 | Posted: 25-10-2021



Answer 5

Update for Python 3.4+ pathlib that actually answers the question:

from pathlib import Path

relative = Path("mydir/myfile.txt")
absolute = relative.absolute()  # absolute is a Path object

If you only need a temporary string, keep in mind that you can use Path objects with all the relevant functions in os.path, including of course abspath:

from os.path import abspath

absolute = abspath(relative)  # absolute is a str object

Answered by: Chelsea997 | Posted: 25-10-2021



Answer 6

Today you can also use the unipath package which was based on path.py: http://sluggo.scrapping.cc/python/unipath/

>>> from unipath import Path
>>> absolute_path = Path('mydir/myfile.txt').absolute()
Path('C:\\example\\cwd\\mydir\\myfile.txt')
>>> str(absolute_path)
C:\\example\\cwd\\mydir\\myfile.txt
>>>

I would recommend using this package as it offers a clean interface to common os.path utilities.

Answered by: Brianna414 | Posted: 25-10-2021



Answer 7

This always gets the right filename of the current script, even when it is called from within another script. It is especially useful when using subprocess.

import sys,os

filename = sys.argv[0]

from there, you can get the script's full path with:

>>> os.path.abspath(filename)
'/foo/bar/script.py'

It also makes easier to navigate folders by just appending /.. as many times as you want to go 'up' in the directories' hierarchy.

To get the cwd:

>>> os.path.abspath(filename+"/..")
'/foo/bar'

For the parent path:

>>> os.path.abspath(filename+"/../..")
'/foo'

By combining "/.." with other filenames, you can access any file in the system.

Answered by: Arthur511 | Posted: 25-10-2021



Answer 8

You can use this to get absolute path of a specific file.

from pathlib import Path

fpath = Path('myfile.txt').absolute()

print(fpath)

Answered by: Anna701 | Posted: 25-10-2021



Answer 9

if you are on a mac

import os
upload_folder = os.path.abspath("static/img/users")

this will give you a full path:

print(upload_folder)

will show the following path:

>>>/Users/myUsername/PycharmProjects/OBS/static/img/user

Answered by: Oliver861 | Posted: 25-10-2021



Answer 10

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?

I would do it like this,

import os.path
os.path.join( os.getcwd(), 'mydir/myfile.txt' )

That returns '/home/ecarroll/mydir/myfile.txt'

Answered by: Brad439 | Posted: 25-10-2021



Answer 11

In case someone is using python and linux and looking for full path to file:

>>> path=os.popen("readlink -f file").read()
>>> print path
abs/path/to/file

Answered by: Elise302 | Posted: 25-10-2021



Similar questions

How to Run a Python file from Java using an Absolute Path?

I want to run a python script called, for example foo. And I have the absoulute path, lets say: /Users/me/pythonscripts/ I have tried running: String cmd="/Users/me/pythonscripts/" String py="foo" Runtime.getRuntime().exec("cd "+cmd); Runtime.getRuntime().exec("python "+py+".py"); But that does run the python file.


Get value in XML file through absolute value in Python

I have an absolute path for the values of XML files I want to retrieve. The absolute path is in the format of "A/B/C". How can I do this in Python?


python - File not found at absolute path

I have a script that creates a file and moves it via os.rename, The file is generated while the script is running, however when I go to open the file I get os.rename(str(PATH_TO_PROGRAM)+str("Outputs/important_output.txt"), str(args['output_dir'])+ str("important_output.txt")) with open(str(args['output_dir'])+str("important_output.txt), "r") as infile: d...


python - how to get the absolute path to the root folder

This is my current folder structure, and i need to get the absolute path to the root folder . └── root/ ├── api.py └── programexecutablefolder/ └── mainentry.py The program has to start at mainentry.py, however I need to get the path of the root folder from api.py (though the entry to api.py is through mainentry.py) Also os.getcwd() doesn't work as it w...


python - How to add a to the absolute value of b without call abs

I'm having a little problem defining a function. I'm trying to add a to the absolute value of b without calling abs from operator import add, sub def a_plus_absolute_b(a, b): """Return a+abs(b), but without calling abs.""" if b < 0: op = add(a, (b * -1)) else: op = add(a, b) return op(a, b)


How can I check if a URL is absolute using Python?

What is the preferred solution for checking if an URL is relative or absolute?


Python xml absolute path

How do I use python to print/dump the "absolute path" and value for an XML document? for example: <A> <B>foo</B> <C> <D>On</D> </C> <E>Auto</E> <F> <G> <H>shoo</H> <I>Off</I> </G> </F> </A> to /A/B, foo /A/C/D, On /A/E, Auto...


Why do python .pyc files contain the absolute path of their source code?

Why do python .pyc files contain the absolute path of their source code, instead of a relative path or something else? A typical __init__.pyc from Python 2.7 on Ubuntu: \ufffd\ufffd\ufffdOc@sddlTdS(i\ufffd\ufffd\ufffd\ufffd(t*N(tdbapi2(((s&/usr/lib/python2.7/sqlite3/__init__.py<module>s


python - Why we need to specify absolute path in Bottle + uWSGI?

I'm developing a Bottle application. My program reads configurations from configuration (.cfg) files and also using template (.tpl) files. But when I host my app on nginx using uWSGI, it cannot find the files (given relative paths to the project) What is the possible solution??


python - Get Absolute URL in Django when using Class Based Views

Hello I am migrating my app to use class based views instead of function based views. In my old code I was able to get the absolute URL of an object related to a function view this way: class Category(models.Model): name = models.CharField(max_length=100,unique=True) slug = models.SlugField(unique=True) description = models.TextField() parent = models.ForeignKey('self',null=True,blank=True) ...


python - Specify absolute colour for 3D points in MayaVi

I am using the MayaVi Python library to plot 3d points, using the points3d class. The documentation specifies that the colour of each point is specified through a fourth argument, s:


python - how to get the absolute url of a view in django?

I have a view called "callback" in views.py. How can I get the absolute url with domain for that view? I tried using: request.build_absolute_url(reverse('authorize')) but that did not work. What should I do?


python - How to sort a list and put it in absolute value

I have this list that contains positive and negative elements but now I need to sort the list and put it in absolute value, for example: list[-2,-3,8,-5,1,7]===>list[1,2,3,5,7,8] Is it clear? The code: a=5 b=6 c=-3 d=-8 lista = [a,b,c,d] lista.sort() lista.reverse()


python - Another absolute import problem

I'm having problems with my own modules overriding built in Python ones (specifically the logging module). Here's my project layout: run.py package/ __init__.py logging/ __init__.py ... run.py from package import main main() package/__init__.py from __future__ import absolute_import import logging i...


python - How to scroll a tkinter canvas to an absolute position?

I'm using Python and tkinter. I have a Canvas widget that will display just one image. Most times the image will be larger than the canvas dimensions, but sometimes it will be smaller. Let's just focus on the first case (image larger than canvas). I want to scroll the canvas to an absolute position that I have already calculated (in pixels). How can I do that?


python - how to get the absolute path to the root folder

This is my current folder structure, and i need to get the absolute path to the root folder . └── root/ ├── api.py └── programexecutablefolder/ └── mainentry.py The program has to start at mainentry.py, however I need to get the path of the root folder from api.py (though the entry to api.py is through mainentry.py) Also os.getcwd() doesn't work as it w...


Why doesn't this absolute import work in Python?

I've got two Python 2.6 files, /code/x/X.py: import imp print 'running' logging = imp.load_source('logging', '/code/y/logging.py') ... and /code/y/logging.py: from __future__ import absolute_import import logging as _logging import sys, os print sys.path print os.getcwd() print _logging Running X.py prints:


Python command line SETUP for ABSOLUTE BEGINNER with Python

I'm "new school" meaning that i've never really used the command prompt(they didn't teach us anything but IDE's in school). I would like to setup Python using Notepad++ for the editor, and winpdb as my debugger. I want stuff to work really easy from the cmd prompt but it is not. This is what I put in my System Environment: C:\PYTHON27;C:\PYTHON27\DLLs;C:\PYTHON27\LIB;C:\PYTHON27\LIB\LIB-TK;C:\PYTHON27\LIB\S...


python - When to use absolute imports

I'm changing a bunch of old python code that is occasionally running into name collisions between packages. I have a question about when absolute imports should be used and whether it would be proper to import same-level modules by name only. /package/ /package/__init__.py /package/subA /package/subA/__init__.py /package/subA/moduleA.py /package/subA/moduleB.py /package/subB /package/subB/__init__.py /pack...


python - How to add a to the absolute value of b without call abs

I'm having a little problem defining a function. I'm trying to add a to the absolute value of b without calling abs from operator import add, sub def a_plus_absolute_b(a, b): """Return a+abs(b), but without calling abs.""" if b < 0: op = add(a, (b * -1)) else: op = add(a, b) return op(a, b)


django - Getting absolute file/dir path in python

From the code below both returns me the same output. When should I use one over the other? import os from os.path import abspath, dirname print abspath(dirname(__file__)) print os.getcwd() PS: I wanted to use this for dynamically changing the path for logs, static files and templates in my django project to run it in different environments.


search - finding absolute path from a relative path in python

my question is pretty much what the title suggests. my research has led me to try something like this: import os pathname = os.path.abspath("some/relative/directory") print pathname this problem is that whenever i do something like this, it simply returns whatever relative directory i gave it preceded by my python directory. for example: C:\Python27\some\relative\directory


python - How to join absolute and relative urls?

I have two urls: url1 = "http://127.0.0.1/test1/test2/test3/test5.xml" url2 = "../../test4/test6.xml" How can I get an absolute url for url2?






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top