python獲取文件大小,python計算目錄大小_使用Python計算目錄的大小?

 2023-11-18 阅读 29 评论 0

摘要:Before I re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.解決方案This walks all sub-directories; summing f

Before I re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.

解決方案

This walks all sub-directories; summing file sizes:

import os

python獲取文件大小。def get_size(start_path = '.'):

total_size = 0

for dirpath, dirnames, filenames in os.walk(start_path):

for f in filenames:

fp = os.path.join(dirpath, f)

python創建目錄,# skip if it is symbolic link

if not os.path.islink(fp):

total_size += os.path.getsize(fp)

return total_size

print(get_size(), 'bytes')

python爬蟲教程。And a oneliner for fun using os.listdir (Does not include sub-directories):

import os

sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f))

Reference:

Updated

python 類、To use os.path.getsize, this is clearer than using the os.stat().st_size method.

Thanks to ghostdog74 for pointing this out!

os.stat - st_size Gives the size in bytes. Can also be used to get file size and other file related information.

import os

nbytes = sum(d.stat().st_size for d in os.scandir('.') if d.is_file())

python下載。Update 2018

If you use Python 3.4 or previous then you may consider using the more efficient walk method provided by the third-party scandir package. In Python 3.5 and later, this package has been incorporated into the standard library and os.walk has received the corresponding increase in performance.

Update 2019

Recently I've been using pathlib more and more, here's a pathlib solution:

from pathlib import Path

python3,root_directory = Path('.')

sum(f.stat().st_size for f in root_directory.glob('**/*') if f.is_file())

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/178764.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息