python - open(filepath) 和 open(os.path.abspath(filepath)) 的区别
问题描述
下面这两种说法有什么区别吗?
with open(filepath):
with open(os.path.abspath(filepath)):
解决方案
如果我们问第一行和第二行之间的区别,重要的是要说价值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!
推荐阅读
- laravel - 同一域下多个 Laravel 8 站点之间的用户和会话共享
- php - 使用 PHP 计算两个 8 位日期之间的天数的简单语句?
- psql - 错误:连接到套接字“/tmp/.s.PGSQL.5432”上的服务器失败
- javascript - 使用另一个js文件的Javascript Unerror方法
- python - 更改组合问题:我找到了这段代码,但我无法理解某些行
- python - 应用返回错误消息的函数:“时间戳”对象不可下标
- javascript - Vaadin 14 Springboot javascript不起作用
- ios - 安装 Cocoapods 时出错:[!] Invalid `Podfile` 文件:未定义的局部变量或方法 `cocoapods' 用于#
- algorithm - 我的递归记忆解决方案的运行时间是多少
- config - Mosquitto Bridge 主题设置忽略模式