首先得導入os 模塊,path 類屬於os模塊.
To join two or more path components together,首先導入 python 的 os 模塊,Then use the following:
import os
myPath = os.path.join('C:\\','a', 'b', 'c')
print(myPath)
輸出字符串:C:\a\b\c
使用 os.path The advantage is that it allows the code to remain compatible on all operating systems,Because it uses the appropriate separator for the platform it is running on.
p = os.path.join(os.getcwd(),'demo.txt')
print(p)
輸出:D:\PyCODE\Basicknowledge\demo.txt
print(os.path.dirname(p))
輸出:D:\PyCODE\Basicknowledge
print(os.path.basename§)
輸出:demo.txt
print(os.path.split(p))
輸出: (‘D:\PyCODE\Basicknowledge’, ‘demo.txt’)
print(os.path.splitext(p))
輸出:(‘D:\PyCODE\Basicknowledge\demo’, ‘.txt’)
print(os.path.splitext(os.path.basename(p)))
輸出:(‘demo’, ‘.txt’)
if(os.path.exists(p)):
print('Exist')
else:
print("Not")
使用函數 exists() 方法
ph =r'D:\PyCODE\Basicknowledge'
print(ph)
print(os.path.isdir(ph))
fph = os.path.join(ph, 'demo.txt')
fph = ph+"\\demo.txt"
print(fph)
print(os.path.isfile(fph))
p1 = os.getcwd()
print(p1)
輸出: D:\PyCODE\Basicknowledge
print(os.path.abspath("test"))
輸出:D:\PyCODE\Basicknowledge\test
print(os.path.abspath("../test"))
輸出:D:\PyCODE\test
print(os.path.abspath("/test"))
輸出:D:\test