python文件路徑操作方法總結
在python中,文件使用十分頻繁,本文將向大家介紹python文件路徑的操作:得到指定文件路徑、得到當前文件名、判斷文件路徑是否存在、獲得指定文件夾下所有文件、獲得文件后綴、拼接路徑和文件名。
1、得到指定文件路徑:os.path.dirname(帶路徑文件名)
查找處理文件要調用os庫,和openpyxl一樣,先用import 導入。
import osfile = r’e:python刪除最小值.xlsx’pwd = os.path.dirname(file)print(pwd)
運行結果為:
e:python
也可從分離文件名后的列表中提取:os.path.split(帶路徑文件名)[0]
2、得到當前文件名:os.path.dasename(帶路徑文件名)
import osfile = r’e:python刪除最小值.xlsx’pwdn = os.path.basename(file)print(pwdn)
運行結果為:
刪除最小值.xlsx
也可從分離文件名后的列表中提取:os.path.split(帶路徑文件名)[1]
3、判斷文件路徑是否存在:os.path.exists(帶路徑文件名)
import osfile = r’e:python刪除最小值.xlsx’pwdbool = os.path.exists(file)print(pwdbool)
運行結果為:
true
若給定的路徑文件不存在,則返回false
4、獲得指定文件夾下所有文件:print(os.listdir(文件夾路徑))
import ospwdns = os.listdir(r’e:python’)print(pwdns[1])
運行結果:
.py 為’e:python’文件夾下第2個文件(或文件夾)名。
5、獲得文件后綴:os.path.splitext(文件名)
import ospdn= os.path.splitext(‘試驗.py’)print(pdn[1])
運行結果:
.py,若最后一句改為print(pdn[0]),則得到文件名。
6、拼接路徑和文件名:os.path.join(路徑,文件名)
f2 = os.path.join(f1, ‘匯總.xlsx’)
運行結果:
‘e:python匯總匯總.xlsx’
到此這篇關于python文件路徑操作方法總結的文章就介紹到這了,更多相關python文件路徑的操作內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: