雲空間服務,助力使用者資料儲存與協同
python路徑拼接os.path.join()函式的用法
os.path.join()函式:連線兩個或更多的路徑名元件1.如果各元件名首字母不包含’/’,則函式會自動加上
2.如果有一個元件是一個絕對路徑,則在它之前的所有元件均會被捨棄
3.如果最後一個元件為空,則生成的路徑以一個’/’分隔符結尾
Demo1
import os
Path1 = 'home'
Path2 = 'develop'
Path3 = 'code'
Path10 = Path1 + Path2 + Path3
Path20 = os.path.join(Path1,Path2,Path3)
print ('Path10 = ',Path10)
print ('Path20 = ',Path20)
輸出
Path10 = homedevelopcode
Path20 = home\develop\code
--------------------------------------------------------------
Demo2
import os
Path1 = '/home'
Path2 = 'develop'
Path3 = 'code'
Path10 = Path1 + Path2 + Path3
Path20 = os.path.join(Path1,Path2,Path3)
print ('Path10 = ',Path10)
print ('Path20 = ',Path20)
輸出
Path10 = /homedevelopcode
Path20 = /home\develop\code
--------------------------------------------------------------
Demo3
import os
Path1 = 'home'
Path2 = '/develop'
Path3 = 'code'
Path10 = Path1 + Path2 + Path3
Path20 = os.path.join(Path1,Path2,Path3)
print ('Path10 = ',Path10)
print ('Path20 = ',Path20)
輸出
Path10 = home/developcode
Path20 = /develop\code
--------------------------------------------------------------
Demo4
import os
Path1 = 'home'
Path2 = 'develop'
Path3 = '/code'
Path10 = Path1 + Path2 + Path3
Path20 = os.path.join(Path1,Path2,Path3)
print ('Path10 = ',Path10)
print ('Path20 = ',Path20 )
輸出
Path10 = homedevelop/code
Path20 = /code