参考:https://www.cnblogs.com/benben-wu/p/12411316.html
参考:https://blog.csdn.net/w55100/article/details/92081182
参考:https://blog.csdn.net/dbllw8293/article/details/101815959
参考:https://blog.csdn.net/qq_34924407/article/details/83063748
读取文件夹/文件大小
- 读取文件夹大小
其实就是遍历整个文件夹的所有子文件,然后加总getsize的返回值。
os.scandir()
import os
def getFileFolderSize(fileOrFolderPath):
"""get size for file or folder"""
totalSize = 0
if not os.path.exists(fileOrFolderPath):
return totalSize
if os.path.isfile(fileOrFolderPath):
totalSize = os.path.getsize(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 = os.path.getsize(curSubEntryFullPath) # 1891
totalSize += curSubFileSize
return totalSize
normalFile ="/aaa/bbb.ccc"
normalFileSize = getFileFolderSize(normalFile)
print("normalFileSize=%s" % normalFileSize)
userFolder = "/aaa/ddd/"
userFolderSize = getFileFolderSize(userFolder)
print("userFolderSize=%s" % userFolderSize)
#source:https://github.com/crifan/crifanLibPython/blob/master/crifanLib/crifanFile.py
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)
- 读取文件大小 os.path.getsize() fileobj.tell() os.stat().st_size
import os
path='/hha/dd.k'
sz = os.path.getsize(path)
print(sz)
统计文件数目
import os
count = 0
# 遍历文件夹
def walkFile(file):
for root, dirs, files in os.walk(file):
# root 表示当前正在访问的文件夹路径
# dirs 表示该文件夹下的子目录名list
# files 表示该文件夹下的文件list
# 遍历文件
for f in files:
global count
count += 1
print(os.path.join(root, f))
# 遍历所有的文件夹
for d in dirs:
print(os.path.join(root, d))
print("文件数量一共为:", count)
if __name__ == '__main__':
walkFile(r"E:\test")