连接路径时我通常使用“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
结果:
最佳答案
您可以通过 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/