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

Arraysinpython, 특히 비밀 복구를위한 ArecrucialInscientificcomputing.1) theaRearedFornumericalOperations, DataAnalysis 및 MachinELearning.2) Numpy'SimplementationIncensuressuressurations thanpythonlists.3) arraysenablequick

Pyenv, Venv 및 Anaconda를 사용하여 다양한 Python 버전을 관리 할 수 있습니다. 1) PYENV를 사용하여 여러 Python 버전을 관리합니다. Pyenv를 설치하고 글로벌 및 로컬 버전을 설정하십시오. 2) VENV를 사용하여 프로젝트 종속성을 분리하기 위해 가상 환경을 만듭니다. 3) Anaconda를 사용하여 데이터 과학 프로젝트에서 Python 버전을 관리하십시오. 4) 시스템 수준의 작업을 위해 시스템 파이썬을 유지하십시오. 이러한 도구와 전략을 통해 다양한 버전의 Python을 효과적으로 관리하여 프로젝트의 원활한 실행을 보장 할 수 있습니다.

Numpyarrayshaveseveraladvantagesstandardpythonarrays : 1) thearemuchfasterduetoc 기반 간증, 2) thearemorememory-refficient, 특히 withlargedatasets 및 3) wepferoptizedformationsformationstaticaloperations, 만들기, 만들기

어레이의 균질성이 성능에 미치는 영향은 이중입니다. 1) 균질성은 컴파일러가 메모리 액세스를 최적화하고 성능을 향상시킬 수 있습니다. 2) 그러나 유형 다양성을 제한하여 비 효율성으로 이어질 수 있습니다. 요컨대, 올바른 데이터 구조를 선택하는 것이 중요합니다.

tocraftexecutablepythonscripts, 다음과 같은 비스트 프랙티스를 따르십시오 : 1) 1) addashebangline (#!/usr/bin/envpython3) tomakethescriptexecutable.2) setpermissionswithchmod xyour_script.py.3) organtionewithlarstringanduseifname == "__"

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

WebStorm Mac 버전
유용한 JavaScript 개발 도구

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.
