程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Path class in Python

編輯:Python

首先得導入os 模塊,path 類屬於os模塊.

1. Joinmethod to create path

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.

2. Path string manipulation

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’)

3. 判斷路徑是否存在

if(os.path.exists(p)):
print('Exist')
else:
print("Not")

使用函數 exists() 方法

4. Determines whether the path is a path or a file

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))

5. 相對路徑和絕對路徑

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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved