Python的os.path裡面的函式
阿新 • • 發佈:2022-03-24
1.獲取當前檔案資料夾絕對路徑
path = os.path.dirname(__file__)
path = os.getcwd()
1 import os
2
3 path = os.path.dirname(__file__) # 獲取當前檔案所在的檔案目錄(結對路徑)
4 print(path)
5
6 # >> D:/PythonProject/Python基礎
2.獲取檔名稱和路徑拼接
path1 = os.path.join(path, imgname)
join可以拼接多級
os.join(path,'project','imgname') --> path/project/imgnae
1 with open(r'E:\girl.jpg', 'rb') as f: 2 img = f.read() 3 print(f.name) 4 imgname = f.name[f.name.rfind('\\') + 1:] # 獲取檔名稱 5 print(imgname) 6 path = os.path.dirname(__file__) 7 path1 = os.path.join(path, imgname) # 拼接路徑 8 with open(path1, 'wb') as f1: 9 f1.write(img) 10 11 print('複製成功')
3.判斷當前路徑
1 r = os.path.isabs(r'E:\girl.jpg') # 判斷該檔案的路徑是否是絕對路徑
2 print(r)
# >> True
3
4 r = os.path.isabs('../img/girl.jpg') # ../表示返回當前檔案的上一級
5 print(r)
# >> False
6
7 r = os.path.isabs('img/girl.jpg') # 找到當前檔案同級的img裡面的girl.jpg
8 print(r)
# >> False
4.通過相對路徑獲取絕對路徑
path = os.path.abspath(檔名稱)
1 # 通過相對路徑獲取檔案的絕對路徑
2 path = os.path.abspath('girl.jpg')
3 print(path)
4 # >> D:\PythonProject\Python基礎\girl.jpg
5.獲取當前檔案的絕對路徑
path = os.path.abspath(__file__)
1 # 獲取本檔案的絕對路徑 2 path = os.path.abspath(__file__) 3 print(path) 4 # >> D:\PythonProject\Python基礎\OS模組.py
6.獲取檔名稱(2.0)和split分割
result = os.path.split(path)
後面path為檔案的路徑,返回一個元祖型別
1 # 獲取檔名稱
2 path = r'D:\PythonProject\Python基礎\OS模組.py'
3 result = os.path.split(path)
4 print(type(result))
5 print(result)
6 # >> <class 'tuple'>
7 # ('D:\\PythonProject\\Python基礎', 'OS模組.py')
8
9 print(result[1])
10 # >> OS模組.py
result = os.path.splitext(path) # 分割檔案與副檔名
1 # 獲取副檔名 2 path = r'D:\PythonProject\Python基礎\OS模組.py' 3 result = os.path.splitext(path) # 分割檔案與副檔名 4 print(result) 5 print(result[1]) 6 7 # >> ('D:\\PythonProject\\Python基礎\\OS模組', '.py') 8 # .py
7.獲取檔案大小
size = os.path.getsize(path)
path為檔案的路徑
1 # 獲取檔案的大小 單位:位元組
2 path = r'D:\PythonProject\Python基礎\OS模組.py'
3 size = os.path.getsize(path)
4 print(size)
5
6 # >> 1694