使用os.path.join和os.sep连接的区别

2024-05-15 10:04:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我在试着找出它是否更适合使用:

os.path.join(str1, str2)

或:

str1 + os.sep + str2

使用timeit进行分析发现,正如预期的那样,连接速度更快:

%timeit 'playground' + os.sep + 'Text'
10000000 loops, best of 3: 139 ns per loop

%timeit os.path.join('playground', 'Text')
1000000 loops, best of 3: 830 ns per loop

所以我的问题是,由于连接也更短,有没有理由使用os.path.join(()

谢谢


Tags: ofpathtextloopossepbestns
2条回答

就在文件里:

os.path.join(path1[, path2[, ...]])

Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return value is the concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) following each non-empty part except the last. (This means that an empty last part will result in a path that ends with a separator.) Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

os.path.join做的更多:

>>> os.path.join("/home/", "/home/foo")
'/home/foo'
>>> "/home/" + os.sep + "/home/foo"
'/home///home/foo'

您永远不会遇到os.path.join是程序瓶颈的情况,因此使用它,它的可读性也会大大提高。

os.path.join接受多个参数:

import os
os.path.join('a', 'b', 'c')

对于许多路径部分,这将变得相当长。

相关问题 更多 >