首页 > 解决方案 > open(filepath) 和 open(os.path.abspath(filepath)) 的区别

问题描述

下面这两种说法有什么区别吗?

with open(filepath):

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

标签: python

解决方案


如果我们问第一行和第二行之间的区别,重要的是要说价值filepath是什么。

该行为在文档中进行了描述,并且可以轻松测试。

# 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 

符号链接有不同的行为,绝对路径是指从文件系统根目录开始的路径,而不是到目标的路径。这就是为什么我们有os.path.realpath,它总是返回目标的“物理”路径。

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

输出:

File /tmp/file_b contains: Hello world!
File /tmp/file_b contains: Hello world!
File /tmp/file_a contains: Hello world!

推荐阅读