设为首页 加入收藏

TOP

Python 标准库
2019-01-24 02:53:37 】 浏览:41
Tags:Python 标准

Python丰富而强大遍历的标准库是其最突出的优点之一.

这里当然不可能说明所有的标准库, 本文只简单列出一些标准库的使用, 还有一部分在其它博文中说明:

操作系统环境os

建议使用 import os 风格而非 from os import *。这样可以保证随操作系统不同而有所变化的 os.open() 不会覆盖内置函数 open()

在使用 os 这样的大型模块时内置的 dir()help() 函数非常有用。

命令行参数sys

通用工具脚本经常调用命令行参数。这些命令行参数以链表形式存储于 sys 模块的 argv 变量。

sys 还有 stdin,stdout 和 stderr 属性,即使在 stdout 被重定向时,后者也可以用于显示警告和错误信息。

>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one

数学math

数据压缩zlib

以下模块直接支持通用的数据打包和压缩格式:zlib,gzip,bz2,zipfile,以及 tarfile。

>>> import zlib
>>> s = b'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979

性能测试timeit

>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791

文件通配符glob

glob模块提供了一个函数用于从目录通配符搜索中生成文件列表:

>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']  

高精度小数 decimal

decmial模块可以提供制定精度的小数运算,使用前需要>>>import decmial。decmial对象由构造函数decmial.Decmial()根据一个int或字符串参数建立。Python3.5中decmial.Decmial()可以根据float建立对象,但那是不精确的。

>>>decimal.Decimal(1)
Decimal('1')
>>>decimal.Decimal("1.2")
Decimal('1.2')

math与cmath库中的数学函数对decimal不适用,但decimal自身提供了一系列数学函数。

>>> x = decimal.Decimal(2)
>>> x.exp()
Decimal('7.389056098930650227230427461')
>>> decimal.Decimal.exp(x)
Decimal('7.389056098930650227230427461')

对象序列化pickle

Python的pickle模块实现了基本的数据序列和反序列化。
序列化:

import pickle
pickle.dump(obj, file, [,protocol])

反序列化:

obj = pickle.load(file)
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇系列文章--Python Web编程 下一篇Python中sys.path.append和os.env..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目