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