os.path.join
用于将多个路径拼接为一个完整路径。经常使用,但没了解过细节,直到今天遇到一个令人疑惑的问题,最后发现是os.path.join
的问题,借此机会,记录下os.path.join
的用法。
os.path.join()
method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator (‘/’) following each non-empty part except the last path component. If the last path component to be joined is empty then a directory separator (‘/’) is put at the end.
If a path component represents an absolute path, then all previous components joined are discarded and joining continues from the absolute path component.
总的来讲,os.path.join
可以拼接的path分为以下三种:
'/'
开头的路径'/'
开头的路径对于这三种不同类型的path,os.path.join
有不同的处理方式:
'/'
;如果是最后一个,则保持原样os.path.join
总是从绝对路径开始拼接'/'
p1 = 'home/Desktop'
p2 = 'tmp'
p3 = '/home'
p4 = ''
path1 = os.path.join(p1, p2) # 两个相对路径
path2 = os.path.join(p1, p2, p3) # 绝对路径前的结果被丢弃
path3 = os.path.join(p1, p4,p2, p4) # 空字符串在最后一项,则在拼接结果中添加/
输出:
path1: home/Desktop/tmp
path2: /home
path3: home/Desktop/tmp/