0

Is there any difference between these 2 statements below?

with open(filepath):

with open(os.path.abspath(filepath)):

Valentyn
  • 562
  • 1
  • 7
  • 21
  • Does this answer your question? [Why would one use both, os.path.abspath and os.path.realpath?](https://stackoverflow.com/questions/37863476/why-would-one-use-both-os-path-abspath-and-os-path-realpath) – clubby789 Jan 16 '20 at 13:48
  • Talking about code behaviour there is no difference at all. Os.path.abspath converts a relative.filepath to absolite path, that's all. Hope this helps – Guillem Jan 16 '20 at 13:48
  • Abspath removes relative symbols like `.` and `..` – clubby789 Jan 16 '20 at 13:48
  • 2
    @JammyDodger Not quite, completely replacing the relative path with the absolute. From `~ / .bashrc` it will make `/home/usr/.bashrc` as from `.bashrc` (if we are at HOME) it will make `/home/usr/.bashrc`. – Geekmoss Jan 16 '20 at 13:50

1 Answers1

0

If we ask the difference between the first and second line, it is important to say what the value of filepath is.

The behavior is described in the documentation and can be easily tested.

# env: HOME=/home/usr, PWD=/home/usr
from os.path import abspath


filepath1 = ".bashrc"
print(filepath1, abspath(filepath1), sep=" -> ")
# Output: .bashrc -> /home/usr/.bashrc

filepath2 = "~/.bashrc"
print(filepath2, abspath(filepath2), sep=" -> ")
# Output: ~/.bashrc -> /home/usr/.bashrc

filepath3 = "../usr/.bashrc"
print(filepath3, abspath(filepath3), sep=" -> ")
# Output: ../usr/.bashrc -> /home/usr/.bashrc

filepath4 = "/home/usr/.bashrc"
print(filepath4, abspath(filepath4), sep=" -> ")
# Output: /home/usr/.bashrc -> /home/usr/.bashrc

filepath5 = "/tmp/tempfile.txt"
print(filepath5, abspath(filepath5), sep=" -> ")
# Output: /tmp/tempfile.txt -> /tmp/tempfile.txt 

There is a different behavior in symlinks, the absolute path means the path from the root of the filesystem, not the path to the target. That's why we have os.path.realpath, which always returns the "physical" path to the target.

echo "Hello world!" > /tmp/file_a
ln -s /tmp/file_a /tmp/file_b
from os.path import abspath, realpath

path = "/tmp/file_b"

with open(path) as f:
    print(f"File {path} contains: {f.read()}")
    pass

with open(abspath(path)) as f:
    print(f"File {abspath(path)} contains: {f.read()}")
    pass

with open(realpath(path)) as f:
    print(f"File {realpath(path)} contains: {f.read()}")
    pass

Output:

File /tmp/file_b contains: Hello world!
File /tmp/file_b contains: Hello world!
File /tmp/file_a contains: Hello world!
Geekmoss
  • 637
  • 6
  • 11