Is there any difference between these 2 statements below?
with open(filepath):
with open(os.path.abspath(filepath)):
Is there any difference between these 2 statements below?
with open(filepath):
with open(os.path.abspath(filepath)):
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!