1. 程式人生 > 其它 >獲取檔案基本資訊

獲取檔案基本資訊

技術標籤:python

獲取檔案基本資訊

格式化時間的函式

def formatTime(longtime):
    '''格式化時間的函式'''
    import time
    return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(longtime))

格式化位元組的函式

def formatByte(number):
    '''格式化檔案大小的函式,將位元組轉換成KB,MB,GB'''
    for (scale,label) in
[(1024*1024*1024,"GB"),(1024*1024,"MB"),(1024,"KB")]: if number >= scale: # 大於等於1KB return "%.2f %s" %(number*1.0/scale,label) elif number == 1: return "1 位元組" else: # 小於1KB byte =
"%.2f" %(number or 0) return (byte[:-3] if byte.endswith(".00") else byte) + "位元組" # [:-3]主要是為了去掉尾部的.00,主要處理小於1KB的情況 # 條件值為真值時,[:-3]代表結束位置倒數第三個

完整程式碼

import os
def formatTime(longtime):
    '''格式化時間的函式'''
    import time
    return time.strftime("%Y-%m-%d %H:%M:%S"
,time.localtime(longtime)) def formatByte(number): '''格式化檔案大小的函式,將位元組轉換成KB,MB,GB''' for (scale,label) in [(1024*1024*1024,"GB"),(1024*1024,"MB"),(1024,"KB")]: if number >= scale: # 大於等於1KB return "%.2f %s" %(number*1.0/scale,label) elif number == 1: return "1 位元組" else: # 小於1KB byte = "%.2f" %(number or 0) return (byte[:-3] if byte.endswith(".00") else byte) + "位元組" # [:-3]主要是為了去掉尾部的.00,主要處理小於1KB的情況 # 條件值為真值時,[:-3]代表結束位置倒數第三個 fileinfo = os.stat("1.jpg") # 獲取檔案的基本資訊 print("檔案完整路徑:",os.path.abspath("1.jpg")) # 輸出檔案的基本資訊 print("索引號:",fileinfo.st_ino) print("裝置名:",fileinfo.st_dev) print("檔案大小:",formatByte(fileinfo.st_size)) print("建立時間:",formatTime(fileinfo.st_ctime)) print("最後一次訪問時間:",formatTime(fileinfo.st_atime)) print("最後一次修改時間時間:",formatTime(fileinfo.st_mtime))