在数据库中存储时,使用 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实现文件大小输出的相关知识,希望本文分享对大家有所帮助。

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

heouttemptemptostoreavure ofthewrongdatatypeinapythonarray、yure counteractypeerror.thisduetothearraymodule'sstricttypeeencultionyを使用します

PythonListSarePartOfThestAndardarenot.liestareBuilting-in、versatile、forStoringCollectionsのpythonlistarepart。

theScriptisrunningwithwrongthonversionduetorectRectDefaultEntertersettings.tofixthis:1)CheckthedededefaultHaulthonsionsingpython - versionorpython3-- version.2)usevirtualenvironmentsbycreatingonewiththon3.9-mvenvmyenv、andverixe

PythonArraysSupportVariousoperations:1)SlicingExtractsSubsets、2)Appending/ExtendingAdddesements、3)inSertingSelementSatspecificpositions、4)remvingingDeletesements、5)sorting/verversingsorder、and6)listenionsionsionsionsionscreatenewlistsebasedexistin

numpyarraysAressertialentionsionceivationsefirication-efficientnumericalcomputations andDatamanipulation.theyarecrucialindatascience、mashineelearning、物理学、エンジニアリング、および促進可能性への適用性、scaledatiencyを効率的に、forexample、infinancialanalyyy

UseanArray.ArrayOverAlistinPythonは、Performance-criticalCode.1)homogeneousdata:araysavememorywithpedelements.2)Performance-criticalcode:Araysofterbetterbetterfornumerumerumericaleperations.3)interf

いいえ、notallistoperationSaresuptedbyarrays、andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorintorintorinsertizizing、whosimpactsporformance.2)リスト


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

mPDF
mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

MantisBT
Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

ホットトピック









