search
HomeBackend DevelopmentPython Tutorial基于Python实现文件大小输出

在数据库中存储时,使用 Bytes 更精确,可扩展性和灵活性都很高。

输出时,需要做一些适配。

1. 注意事项与测试代码

1.需要考虑 sizeInBytes 为 None 的场景。

2.除以 1024.0 而非 1024,避免丢失精度。

实现的函数为 getSizeInMb(sizeInBytes),通用的测试代码为

def getSizeInMb(sizeInBytes):
return 0
def test(sizeInBytes):
print '%s -> %s' % (sizeInBytes, getSizeInMb(sizeInBytes))
test(None)
test(0)
test(10240000)
test(1024*1024*10) 

2. 以 MB 为单位输出 -- 返回 float

通常,电子书的大小在 1 - 50MB 之间,输出时统一转为 MB 是不错的选择。

弊端:

1.输出精度过高,比如 10240000 Bytes 计算结果为 10240000 -> 9.765625

2.文件大小有限制,小于 1 MB 或 G 级数据不适合该方式展示

优势:

1.适合于用返回值参与计算

def getSizeInMb(sizeInBytes):
return (sizeInBytes or 0) / (1024.0*1024.0) 

3. 以 MB 为单位保留 1 位小数 -- 返回 str

处于精度问题考虑,可以选择保留 1 位小数。

def getSizeInMb(sizeInBytes):

return '%.1f' % ((sizeInBytes or 0) / (1024.0*1024.0), ) # use 1-dimension tuple is suggested

返回值建议写成 '%.1f' % (number,) 而非 '%.1f' % (number)

二者均能正确执行,但后者容易被误判为执行只有一个参数 number 的函数,导致难以判断的错误。

3. 以 MB 为单位保留至多 1 位小数 -- 返回 str

大多数操作系统一般展示至多 1 位小数

def getSizeInMb(sizeInBytes):
sizeInMb = '%.1f' % ((sizeInBytes or 0) / (1024.0*1024.0), ) # use 1-dimension tuple is suggested
return sizeInMb[:-2] if sizeInMb.endswith('.0') else sizeInMb # python2.5+ required 

4. 自动选择最佳单位

def getSizeInNiceString(sizeInBytes):
"""
Convert the given byteCount into a string like: 9.9bytes/KB/MB/GB
"""
for (cutoff, label) in [(1024*1024*1024, "GB"),
(1024*1024, "MB"),
(1024, "KB"),
]:
if sizeInBytes >= cutoff:
return "%.1f %s" % (sizeInBytes * 1.0 / cutoff, label)
if sizeInBytes == 1:
return "1 byte"
else:
bytes = "%.1f" % (sizeInBytes or 0,)
return (bytes[:-2] if bytes.endswith('.0') else bytes) + ' bytes' 

算法说明:

1. 从英语语法角度,只有 1 使用单数形式。其他 0/小数 均使用复数形式。涉及 bytes 级别

2. 精度方面,KB 及以上级别,保留 1 位小数。bytes 保留至多 1 位小数。

这种处理规则,不适合于小数十分位为 0 的情况,比如 10.0 bytes,10.01 bytes。输入结果均为 10 bytes。

其他情况下,精度均不存在问题。

测试数据与结果如下图

以上内容给大家介绍了基于Python实现文件大小输出的相关知识,希望本文分享对大家有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data types can be stored in a Python array?What data types can be stored in a Python array?Apr 27, 2025 am 12:11 AM

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

What happens if you try to store a value of the wrong data type in a Python array?What happens if you try to store a value of the wrong data type in a Python array?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Which is part of the Python standard library: lists or arrays?Which is part of the Python standard library: lists or arrays?Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

What should you check if the script executes with the wrong Python version?What should you check if the script executes with the wrong Python version?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function