37

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
3
  • What function needs a string? By total path do you mean the absolute path like /home/foo/myapp? Can you show an example? Commented Feb 3, 2014 at 1:46
  • Yes, by total path I mean absolute path. The function that needs a string is SFTPClient.open from paramiko module. Thank you for your answer. Commented Feb 3, 2014 at 1:55
  • 2
    So you need filename to be a string? As a side note, you're overriding the name path with path = path('~/folder/'). A better name would be folder_path = ... Commented Feb 3, 2014 at 3:00

2 Answers 2

30

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
Sign up to request clarification or add additional context in comments.

3 Comments

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.
But abspath is not used in the example(?).
why do i only see .absolute() method?
16

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

1 Comment

pathlib.Path.absolute() doesn't return a string; it returns a PosixPath/WindowsPath object.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.