首先得导入os 模块,path 类属于os模块。
要将两个或多个路径组件连接在一起,首先导入 python 的 os 模块,然后使用以下内容:
import os
myPath = os.path.join('C:\\','a', 'b', 'c')
print(myPath)
输出字符串:C:\a\b\c
使用 os.path 的优点是它允许代码在所有操作系统上保持兼容,因为它使用适用于其运行平台的分隔符。
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