python - 为什么 "os.sep"比 "os.path.join()"快?

标签 python python-3.x

连接路径时我通常使用“os.path.join()”,很少使用“os.sep”。 但我发现“os.sep”比“os.path.join()”更快。为什么?

我的测试代码:

import os
import time

a = 'E:\\video'
b = 'image'
c = '0001.jpg'
start = time.clock()
d = os.path.join(a,b,c)
end = time.clock()
print("%f " % (end - start)) #0.000011
print(d) #E:\video\image\0001.jpg
start = time.clock()
e = a+os.sep+b+os.sep+c
end = time.clock()
print("%f " % (end - start)) #0.000001 
print(e) #E:\video\image\0001.jpg

结果:

enter image description here

最佳答案

您可以通过 reading the source (windows version) 自行回答这个问题- 或者甚至只是文档 FWIW:

Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that 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() 所做的事情远比单纯的字符串连接要多,所以是的,显然它更慢。

关于python - 为什么 "os.sep"比 "os.path.join()"快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48701235/

相关文章:

python正则表达式查找跨越多行的多行C注释

Python 脚本不会通过在 Windows 上双击来执行

python - 在 python 中的每个列表列表中 move 特定值(基于该值)

python - 如何从循环中获取 tkinter 条目

Python 困惑——约定、名称和值

python - 使用opencv python在图像上绘制网格线

python - 将 yuv420p 原始数据转换为图像 opencv

python - 按特定列的可能前缀列表过滤数据框

Python 3 : Insertion Sort comparisons counter

python - 如何处理 "un-importing"一个 SINGLE 模块?