【发布时间】:2021-04-15 16:27:12
【问题描述】:
当我需要在脚本中定义文件系统路径时,我使用os.path.join 来保证路径在不同文件系统上是一致的:
from os import path
path_1 = path.join("home", "test", "test.txt")
我也知道有 Pathlib 库基本上是这样做的:
from pathlib import Path
path_2 = Path("home") / "test" / "test.txt"
这两种处理路径的方式有什么区别?哪个更好?
【问题讨论】:
-
基本上这两种方法都可以,真的没多大关系。它可能归结为您喜欢什么语法。就我个人而言,我不喜欢将斜杠“滥用”为路径连接运算符,因此我更喜欢 os.path.join,但这实际上只是一个口味问题。
-
就功能而言,两者都做同样的事情。这主要是您喜欢哪一个的偏好问题。 treyhunner.com/2018/12/why-you-should-be-using-pathlib
-
你可以像
path_2 = Path("home", "test", "test.txt")一样做,忘记斜线
标签: python path os.path pathlib