python中的路徑拼接問題
更新時間:2023年03月03日 09:44:30 作者:酷酷的Herio
這篇文章主要介紹了python中的路徑拼接問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
python路徑拼接
使用:
- os.path.join()函數(shù):連接兩個或更多的路徑名組件
- 如果有一個組件是一個絕對路徑,則在它之前的所有組件均會被舍棄
- 如果最后一個組件為空,則生成的路徑以一個 \ 分隔符結尾
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\
python os.path.join路徑拼接錯誤
ss = 'E:\\Cloud\\20200813105812L\\res\\1\\425' a = '\\8_live_1962854245_export_files\\media' c = os.path.join(ss,a) print(c)
得到的是如下結果:

os.path.join()函數(shù)
連接兩個或更多的路徑名組件:
參數(shù)可能存在多個
從右邊開始數(shù),遇到第一個以”/”開頭的參數(shù),開始拼接,這個參數(shù)左邊的全部丟棄
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
從右邊開始數(shù),遇到第一個以”/”開頭的參數(shù),開始拼接,這個參數(shù)左邊的全部丟棄
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
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Eclipse和PyDev搭建完美Python開發(fā)環(huán)境教程(Windows篇)
這篇文章主要介紹了Eclipse和PyDev搭建完美Python開發(fā)環(huán)境教程(Windows篇),具有一定的參考價值,感興趣的小伙伴可以了解一下。2016-11-11
Python multiprocessing模塊中的Pipe管道使用實例
這篇文章主要介紹了Python multiprocessing模塊中的Pipe管道使用實例,本文直接給出使用實例,需要的朋友可以參考下2015-04-04

