8. Python自定义模块humansize

我们在提取一个文件元信息的时候,经常会使用到获取元信息的size, 但是默认提取出来的是字节为单位计算的大小,我们需要转换成MB或者GB 或者TB的大小。

因此就需要使用到humansize这个模块, 这个模块不是系统内置的, 你可以通过help()查询内置模块是没有这个的模块的。 需要从其他地方导入才可以进行使用。

将下面的文件保存成humansize.py 放在默认python目录下。

 1 '''''Convert file sizes to human-readable form. 
 2  
 3 Available functions: 
 4 approximate_size(size, a_kilobyte_is_1024_bytes) 
 5     takes a file size and returns a human-readable string 
 6  
 7 Examples: 
 8 >>> approximate_size(1024) 
 9 '1.0 KiB' 
10 >>> approximate_size(1000, False) 
11 '1.0 KB' 
12  
13 '''  
14   
15 SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],  
16             1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}  
17   
18 def approximate_size(size, a_kilobyte_is_1024_bytes=True):  
19     '''''Convert a file size to human-readable form. 
20  
21     Keyword arguments: 
22     size -- file size in bytes 
23     a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024 
24                                 if False, use multiples of 1000 
25  
26     Returns: string 
27  
28     '''  
29     if size < 0:  
30         raise ValueError('number must be non-negative')  
31   
32     multiple = 1024 if a_kilobyte_is_1024_bytes else 1000  
33     for suffix in SUFFIXES[multiple]:  
34         size /= multiple  
35         if size < multiple:  
36             return '{0:.1f} {1}'.format(size, suffix)  
37   
38     raise ValueError('number too large')  
39   
40 if __name__ == '__main__':  
41     print(approximate_size(1000000000000, False))  
42     print(approximate_size(1000000000000))  
43   
44 # Copyright (c) 2009, Mark Pilgrim, All rights reserved.  
45 #   
46 # Redistribution and use in source and binary forms, with or without modification,  
47 # are permitted provided that the following conditions are met:  
48 #   
49 # * Redistributions of source code must retain the above copyright notice,  
50 #   this list of conditions and the following disclaimer.  
51 # * Redistributions in binary form must reproduce the above copyright notice,  
52 #   this list of conditions and the following disclaimer in the documentation  
53 #   and/or other materials provided with the distribution.  
54 #   
55 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'  
56 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  
57 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE  
58 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE  
59 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR  
60 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF  
61 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS  
62 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN  
63 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)  
64 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE  
65 # POSSIBILITY OF SUCH DAMAGE. 
 该程序的功能是将以字节为单位的文件大小转换为以更易读形式,如将1024 B转换为1KB
 1 >>> import sys
 2 >>> import os
 3 >>> metadata = os.stat('test.docx')
 4 >>> metadata
 5 nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0L, st_nlink=0, st_uid=0, st_gid=0, st_size=4934265L, st_atime=1472518662L, st_mtime=1469435178L, st_ctime=1472518662L)
 6 >>> metadata.st_size
 7 4934265L
 8 >>> import humansize
 9 >>> humansize.approximate_size(metadata.st_size )
10 '4.0 MiB'
11 >>>