一、os.stat().st_size
os.stat(filePath)
返回讀取指定文件的相關屬性,然后利用 stat
模塊進行處理。
import os
os.stat('data_feather_ys.feather')
# os.stat_result(st_mode=33206, st_ino=3659174697257342, st_dev=2829373452, st_nlink=1, st_uid=0, st_gid=0, st_size=400102338, st_atime=1631499025, st_mtime=1631499025, st_ctime=1631499025)
os.stat('data_feather_ys.feather').st_size
# 400102338
二、os.path.getsize()
返回指定文件的大小,當指定的路徑不存在或者不可訪問,將會拋出異常 os.error
。實現形式:
def getsize(filename):
"""Return the size of a file, reported by os.stat()."""
return os.stat(filename).st_size
如果想達到性能最優,使用 os.stat()
先檢查路徑是否為文件,再調用 st_size
。
如果想要使用 os.path.getsize()
,則必須提前使用 os.path.isfile()
判斷是不是文件,再使用。
三、函數封裝
利用 os.path.getsize()
獲取文件大小(單位:MB)。
import os
def get_FileSize(filePath):
filePath = str(filePath)
fsize = os.path.getsize(filePath)
fsize = fsize / float(1024 * 1024)
return round(fsize, 2)
print(get_FileSize('data_feather_ys.feather'))