使用:
def test2(): s1, s2, s3 = 'home', 'courses', 'test' res = os.path.join(s1, s2, s3) print(res) # home\courses\test s2 = '/courses' res = os.path.join(s1, s2, s3) print(res) # /courses\test s1, s2, s3 = '\home', 'courses', 'test' res = os.path.join(s1, s2, s3) print(res) # \home\courses\test s1, s2, s3 = '\home', 'courses', '' res = os.path.join(s1, s2, s3) print(res) #\home\courses\
home\courses\test
/courses\test
\home\courses\test
\home\courses\
ss = 'E:\\Cloud\\20200813105812L\\res\\1\\425' a = '\\8_live_1962854245_export_files\\media' c = os.path.join(ss,a) print(c)
得到的是如下结果:
连接两个或更多的路径名组件:
参数可能存在多个
从右边开始数,遇到第一个以”/”开头的参数,开始拼接,这个参数左边的全部丢弃
print("0:",os.path.join('\\aaaa','bbbb','ccccc.txt')) print("0:",os.path.join('aaaa','\\bbbb','ccccc.txt')) print("0:",os.path.join('aaaa','bbbb','\\ccccc.txt')) print("0:",os.path.join('aaaa','\\bbbb','\\ccccc.txt')) print("0:",os.path.join('aaaa','/bbbb','\\ccccc.txt')) print("0:",os.path.join('aaaa','/bbbb','/ccccc.txt')) 结果: 0: \aaaa\bbbb\ccccc.txt 0: \bbbb\ccccc.txt 0: \ccccc.txt 0: \ccccc.txt 0: \ccccc.txt 0: /ccccc.txt
从右边开始数,遇到第一个以”/”开头的参数,开始拼接,这个参数左边的全部丢弃
print("1:",os.path.join('aaaa','xxxxxx','./bbb','ccccc.txt')) print("1:",os.path.join('./aaaa','xxxxxx','./bbb','./ccccc.txt')) 结果: 1: aaaa\xxxxxx\./bbb\ccccc.txt 1: ./aaaa\xxxxxx\./bbb\./ccccc.txt
带盘符,/,\各种复杂情况(正式使用前先测试,也可以去看看源码具体是怎么解析的)
# 后面的斜杠反斜杠 print("1:",os.path.join('c:','bbb')) print("1:",os.path.join('c:','bbb/\\','ccccc.txt')) # 未加盘符 print("2:",os.path.join('c','/bbb','ccccc.txt')) # 会以/bbb开头 print("2:",os.path.join('c:','/bbb','ccccc.txt')) # 虽然有反斜杆 但是依旧以C:开头 print("2:",os.path.join('c:/','/bbb','ccccc.txt')) # 多个/只会有一个 # 盘符后面未加斜杠 print("3:",os.path.join('c:','bbb','ccccc.txt')) print("3:",os.path.join('c:/','bbb','ccccc.txt')) 结果: 1: c:bbb 1: c:bbb/\ccccc.txt 2: /bbb\ccccc.txt 2: c:/bbb\ccccc.txt 2: c:/bbb\ccccc.txt 3: c:bbb\ccccc.txt 3: c:/bbb\ccccc.txt
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。