python 獲取檔案和資料夾大小

2022-05-30 19:30:15 字數 1075 閱讀 6907

1、os.path.getsize可以獲取檔案大小

>>> import

os>>> file_name = '

e:\chengd\cd.db

'>>>os.path.getsize(file_name)

10293248

2、獲取資料夾大小,即遍歷資料夾,將所有檔案大小加和。遍歷資料夾使用os.walk函式

os.walk()可以得到乙個三元tupple(dirpath, dirnames, filenames),

1、第乙個為起始路徑,

2、第二個為起始路徑下的資料夾,

3、第三個是起始路徑下的檔案。

其中dirpath是乙個string,代表目錄的路徑,dirnames是乙個list,包含了dirpath下所有子目錄的名字。filenames是乙個list,包含了非目錄檔案的名字。這些名字不包含路徑資訊,如果需要得到全路徑,需要使用os.path.join(dirpath, name).

import

osfrom os.path import

join, getsize

defgetdirsize(dir):

size =0

for root, dirs, files in

os.walk(dir):

size += sum([getsize(join(root, name)) for name in

files])

return

size

if__name__ == '

__main__':

filesize = getdirsize('

e:\chengd')

print('

there are %.3f

' % (filesize / 1024 / 1024 ), '

mbytes in e:\\chengd')

執行結果:

there are 4747.763 mbytes in e:\chengd

python遍歷資料夾和檔案

在python中,檔案操作主要來自os模組,主要方法如下 os.listdir dirname 列出dirname下的目錄和檔案 os.getcwd 獲得當前工作目錄 os.curdir 返回當前目錄 os.chdir dirname 改變工作目錄到dirname os.path.isdir nam...

python遍歷資料夾和檔案

在python中,檔案操作主要來自os模組,主要方法如下 os.listdir dirname 列出dirname下的目錄和檔案 os.getcwd 獲得當前工作目錄 os.curdir 返回當前目錄 os.chdir dirname 改變工作目錄到dirname os.path.isdir nam...

python遍歷資料夾和檔案

在python中,檔案操作主要來自os模組,主要方法如下 os.listdir dirname 列出dirname下的目錄和檔案 os.getcwd 獲得當前工作目錄 os.curdir 返回當前目錄 os.chdir dirname 改變工作目錄到dirname os.path.isdir nam...