1. 程式人生 > >python_獲取檔案及資料夾大小修改時間

python_獲取檔案及資料夾大小修改時間

獲取檔案大小

關鍵函式是

os.path.getsize(file)

獲取資料夾大小

沒有直接的函式,但是可以通過遍歷資料夾,將每個檔案的大小疊加

關鍵函式

for root, dirs, files in os.walk(filePath):
    for f in files:
        fsize += os.path.getsize(os.path.join(root, f))	

python2和python3稍微有點區別,在python2裡面,不能直接將檔案路徑給os.path.getsize(),因為它不識別中文路徑

需要將中文字元轉換一下

unicode(filePath,'utf8'

獲取檔案建立時間,最後修改時間,訪問時間

關鍵函式

os.path.getctime(filePath)#獲取建立時間,返回值是標準時間,需要轉換
os.path.getmtime(filePath)#獲取最後修改時間,返回值是標準時間,需要轉換
os.path.getatime(filePath)#獲取訪問時間,返回值是標準時間,需要轉換

windows上面很奇怪,目前看到的是檔案的建立時間和訪問時間是一致的,但是資料夾的不一樣

最後全部程式碼如下:

# -*- coding: utf-8 -*-
# @Date     : 2018-11-12 14:28:14
# @Author   : Jimy_Fengqi (
[email protected]
) # @Link : https://blog.csdn.net/qiqiyingse # @Version : V1.0 # @pyVersion: 3.6 import os import sys import time,datetime #獲取檔案的大小,結果保留兩位小數 def get_FileSize(filePath): def getsize(filePath): if pyversion == '2': return os.path.getsize(unicode(filePath,'utf8'))#主要處理中文命名的檔案 else: return os.path.getsize(filePath) pyversion=sys.version[0] fsize=0 if os.path.isdir(filePath): #通過walk函式迭代 for root, dirs, files in os.walk(filePath): for f in files: fsize += getsize(os.path.join(root, f)) #如果目錄檔案中包含有中文命名的檔案或者資料夾,那麼使用python2將會報錯,通過walk函式返回的檔案list,並不會轉換中文 else: fsize =getsize(filePath) print(fsize) fsize = fsize/float(1024) if fsize>1024: fsize = fsize/float(1024) return str(round(fsize,2))+'MB' else: return str(round(fsize,2))+'KB' #把時間戳轉化為時間: 1479264792 to 2016-11-16 10:53:12 def TimeStampToTime(timestamp): timeStruct = time.localtime(timestamp) return time.strftime('%Y-%m-%d %H:%M:%S',timeStruct) #獲取檔案的訪問時間 def get_FileAccessTime(filePath): pyversion=sys.version[0] if pyversion == '2': filePath = unicode(filePath,'utf8')#python2需要使用unicode轉換一下 t = os.path.getatime(filePath) return TimeStampToTime(t) #'''獲取檔案的建立時間''' def get_FileCreateTime(filePath): pyversion=sys.version[0] if pyversion == '2': filePath = unicode(filePath,'utf8')#python2需要使用unicode轉換一下 t = os.path.getctime(filePath) return TimeStampToTime(t) #'''獲取檔案的修改時間''' def get_FileModifyTime(filePath): pyversion=sys.version[0] if pyversion == '2': filePath = unicode(filePath,'utf8')#python2需要使用unicode轉換一下 t = os.path.getmtime(filePath) return TimeStampToTime(t) #普通文字檔案 print('建立時間:'+get_FileCreateTime('test.txt')) print('修改時間:'+get_FileModifyTime('test.txt')) print('訪問時間:'+get_FileAccessTime('test.txt')) print('檔案大小:'+ str(get_FileSize('test.txt'))) #音訊檔案 print('建立時間:'+get_FileCreateTime('過火.mp3')) print('修改時間:'+get_FileModifyTime('過火.mp3')) print('訪問時間:'+get_FileAccessTime('過火.mp3')) print('檔案大小:'+ str(get_FileSize('過火.mp3') )) #判斷資料夾大小 print('建立時間:'+get_FileCreateTime('TxtSpliter')) print('修改時間:'+get_FileModifyTime('TxtSpliter')) print('訪問時間:'+get_FileAccessTime('TxtSpliter')) print('檔案大小:'+ str(get_FileSize('TxtSpliter')))