python获取⽂件夹⼤⼩注意,这⾥是属性⾥的⽂件⼤⼩。⽽不是占⽤空间。实际占⽤空间会>⽂件⼤⼩。
想获取占⽤空间貌似需要⽤到shell,暂时没有深⼊研究。
1.获取⽂件⼤⼩的⽅法
1.1 size()
最简单⽆脑常⽤,返回Byte为单位的⼤⼩。
import os
path='/hha/dd.k'
sz = size(path)
print(sz)
1.2  ll()
import os
def getSize(fileobject):
fileobject.seek(0,2) # move the cursor to the end of the file
size = ll()
return size
file = open('myfile.bin', 'rb')
print getSize(file)
1.3 os.stat().st_size
import os
path = '/'
sz = os.stat(path).st_size
2.获取⽂件夹⼤⼩的⽅法
其实就是遍历整个⽂件夹的所有⼦⽂件,然后加总getsize的返回值。
所以核⼼就是如何遍历
python怎么读文件夹下的文件夹2.1 os.scandir()
#直接了现成的轮⼦。不过我不喜欢驼峰命名啊看着好累。
import os
def getFileFolderSize(fileOrFolderPath):
"""get size for file or folder"""
totalSize = 0
if not ists(fileOrFolderPath):
return totalSize
if os.path.isfile(fileOrFolderPath):
totalSize = size(fileOrFolderPath) # 5041481
return totalSize
if os.path.isdir(fileOrFolderPath):
with os.scandir(fileOrFolderPath) as dirEntryList:
for curSubEntry in dirEntryList:
curSubEntryFullPath = os.path.join(fileOrFolderPath, curSubEntry.name)
if curSubEntry.is_dir():
curSubFolderSize = getFileFolderSize(curSubEntryFullPath) # 5800007
totalSize += curSubFolderSize
elif curSubEntry.is_file():
curSubFileSize = size(curSubEntryFullPath) # 1891
totalSize += curSubFileSize
return totalSize
normalFile ="/"
normalFileSize = getFileFolderSize(normalFile)
print("normalFileSize=%s" % normalFileSize)
userFolder = "/aaa/ddd/"
userFolderSize = getFileFolderSize(userFolder)
print("userFolderSize=%s" % userFolderSize)
#source:github/crifan/crifanLibPython/blob/master/crifanLib/crifanFile.py 2.2 os.walk()
def getdirsize(dir):
size = 0
for root, dirs, files in os.walk(dir):
size += sum([getsize(join(root, name)) for name in files])
return size
dirpath = '/aaa/bbb/'
sz = getdirsize(dirpath)
print(sz)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。