How to get the file size in Python
This article introduces you how to get the file size in Python, the content is very detailed, interested friends can refer to, hope to be helpful to you.
#! / usr/bin/python3.4
#-*-coding: utf-8-*-
Import os
# byte bytes converts kb\ m\ g
Def formatSize (bytes):
Try:
Bytes = float (bytes)
Kb = bytes / 1024
Except:
Print ("the incoming bytes are not in the correct format")
Return "Error"
If kb > = 1024:
M = kb / 1024
If M > = 1024:
G = M / 1024
Return "% f G"% (G)
Else:
Return "% f M"% (M)
Else:
Return "f kb"% (kb)
# get file size
Def getDocSize (path):
Try:
Size = os.path.getsize (path)
Return formatSize (size)
Except Exception as err:
Print (err)
# get folder size
Def getFileSize (path):
Sumsize = 0
Try:
Filename = os.walk (path)
For root, dirs, files in filename:
For fle in files:
Size = os.path.getsize (path + fle)
Sumsize + = size
Return formatSize (sumsize)
Except Exception as err:
Print (err)
If _ name__ = = "_ _ main__":
Print (getDocSize (".. / detailhtml/20161103112313.html"))
# 1006.142578kb
Print (getFileSize (".. / data/"))
# 111.856756M
On how to get the file size in Python to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.