I am specifying a relative file path using jacaro's path module.
How can I get the absolute path from this variable as a string?
import path # From https://github.com/jaraco/path.py
path = path.path('~/folder/')
relative_filename = path.joinpath('foo')
# how can I get the absolute path of as a string?
absolute_path = ???
fd = open(absolute_path)
Mark Harrison
306k132 gold badges355 silver badges498 bronze badges
asked Feb 3, 2014 at 1:25
Slot
1,2262 gold badges17 silver badges29 bronze badges
2 Answers 2
filename has a method called abspath that returns an object with the absolute path. You can cast that to a string.
...
from path import Path
folder_path = Path('/home/munk/folder/')
filename = folder_path.joinpath('foo')
absolute_path = filename.abspath()
print(absolute_path) # '/home/munk/folder/foo'
f = open(absolute_path, 'r')
UPDATE 2023年03月24日: Actually use abspath + use the up to date path library
answered Feb 3, 2014 at 3:05
munk
13.2k10 gold badges54 silver badges72 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
micseydel
Calling str() seems weird to me, I might expect something like what repr() would produce. I would have expected an as_string attribute or something.
Peter Mortensen
But abspath is not used in the example(?).
Lei Yang
why do i only see
.absolute() method?Python 3
from pathlib import Path
path = Path('~/folder/foo')
absolute_path = path.absolute().as_posix()
Python 2
import os
absolute_path = os.path.abspath('~/folder/foo').as_posix()
answered May 11, 2023 at 15:18
J'e
3,8965 gold badges39 silver badges69 bronze badges
1 Comment
zoltanctoth
pathlib.Path.absolute() doesn't return a string; it returns a PosixPath/WindowsPath object.lang-py
path = path('~/folder/'). A better name would be folder_path = ...