【Python】內置os.path模塊最常用的一些用法

os.path模塊主要用於文件的屬性獲取,在編程中經常用到,以下是該模塊的幾種常用方法。
更多的方法可以去查看官方文檔:http://docs.python.org/library/os.path.html

# -*- coding:utf-8 -*-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者:cacho_37967865
#博客:https://blog.csdn.net/sinat_37967865
#文件:os_path_model.py
#日期:2020-04-11
#備註:os.path 模塊主要用於獲取文件的屬性。
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
import os

def deal_path():
    file = 'E:\zenglingwei\\test\pic\\test.jpg'

    print('返回絕對路徑-->',os.path.abspath(file))     # E:\zenglingwei\test\pic\1.jpg
    print('返回path的真實路徑-->', os.path.realpath(file))  # E:\zenglingwei\test\pic\1.jpg

    print('返回元組-->',os.path.split(file))           # ('E:\\zenglingwei\\test\\pic', '1.jpg')
    print('返回文件路徑-->',os.path.dirname(file))     # E:\zenglingwei\test\pic
    print('返回文件名-->', os.path.basename(file))     # 1.jpg

    print('返回正確、錯誤-->', os.path.exists(file))    # True
    print('返回文件大小-->', os.path.getsize(file))     # 653803b  如果文件不存在就返回錯誤

    print('返回最近訪問時間-->',os.path.getatime(file))   # 1586593521.9310188
    print('返回文件創建時間-->',os.path.getctime(file))   # 1586593521.9310188
    print('返回最近修改時間-->',os.path.getmtime(file))   # 1586593521.9310188

    print('合併絕對路徑-->',os.path.join(os.path.dirname(file),os.path.basename(file)))   # E:\zenglingwei\test\pic\1.jpg
    print('合併絕對路徑-->', os.path.join('data','logs','test'))  # data\logs\test


if __name__ == '__main__':
    deal_path()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章