os.path.join和os.sep串联使用之间的区别 [英] Differences between use of os.path.join and os.sep concatenation
问题描述
我正在尝试使用它是否更好:
I am trying to figure out if it is better to use:
os.path.join(str1, str2)
或:
str1 + os.sep + str2
使用timeit
进行配置,我发现,按预期的那样,连接速度更快:
Profiling with timeit
I found that, as expected, concatenation is faster:
%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(()
?
So my question is, since concatenation is also shorter, is there a reason to use os.path.join(()
?
谢谢
推荐答案
它就在文档中:
os.path.join(path1[, path2[, ...]])
智能地加入一个或多个路径组件.如果有任何组件是绝对路径,则所有先前的组件(在Windows上,包括先前的驱动器号,如果有的话)都将被丢弃,并继续连接.返回值是path1
以及(可选)path2
等的串联,在每个非空部分之后(除最后一个部分外)都紧跟一个目录分隔符(os.sep
). (这意味着最后一个空白部分将导致路径以分隔符结尾.)请注意,在Windows上,由于每个驱动器都有一个当前目录,因此os.path.join("c:", "foo")
表示相对于驱动器c:foo
),而不是c:\foo
.
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
是程序瓶颈的情况,因此使用它,它也更具可读性.
You will never have a situation where os.path.join
is the bottleneck of your program, so use it, it's much more readable too.
这篇关于os.path.join和os.sep串联使用之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!