Python path as a string

Question:

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)
Asked By: Slot

||

Answers:

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 By: munk
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.