Python3 标准库概览精选
Python3 标准库概览
Python 标准库概览
操作系统接⼜
os模块提供了不少与操作系统相关联的函数。
>>> import os
>>> os.getcwd() # 返回当前的⼯作⽬录
'C:\\Python34 '
>>> os.chdir('/server/access ogs') # 修改当前的⼯作⽬录
>>> os.system('mkdir today ') # 执⾏系统命令 mkdir
0
建议使⽤ "import os" 风格⽽⾮ "from os import *"。这样可以 证随操作系统不同⽽有
所变化的 os.open() 不会覆盖内置函数 open() 。
在使⽤ os 这样的⼤型模块时内置的 dir() 和 help() 函数⾮常有⽤:
>>> import os
>>> dir(os)
>>> he p(os)
针对⽇常的⽂件和⽬录管理任务,:mod:shutil 模块提供了⼀个易于使⽤的⾼级接⼜:
>>> import shuti
>>> shuti .copyfi e('data.db', 'archive.db')
>>> shuti .move('/bui d/executab es', 'insta dir')
⽂件通配符
glob模块提供了⼀个函数⽤于从⽬录通配符搜索中⽣成⽂件列表:
>>> import g ob
>>> g ob.g ob('*.py ')
['primes.py ', 'random.py ', 'quote.py ']
命令⾏参数
通⽤⼯具脚本经常调⽤命令⾏参数。这些命令⾏参数以链表形式存储于 sys 模块的
argv 变量。例如在命令⾏中执⾏ "python demo .py one two three" 后可以得到以下输出
结果:
>>> import sys
>>> print(sys.argv)
['demo.py ', 'one', 'two', 'three']
错误输出重定向和程序 ⽌
sys 还有 stdin ,stdout 和 stderr 属性,即使在 stdout 被重定向时,后者也可以⽤于显⽰
警告和错误信息。
>>> sys.stderr.write('Warning, og fi e not found starting a new o
Warning, og fi e not found starting a new one
⼤多脚本的定向终⽌都使⽤ "sys.exit()"。
字符串正则匹配
re模块为⾼级字符串处理提供了正则表达式⼯具。对于复杂的匹配和处理,正则表达
式提供了简洁、优化的解决⽅案:
>>> import re
>>> re.finda (r'\bf[a-z]*', 'which foot or hand fe fastest')
['foot', 'fe ', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'
如果只需要简单的功能,应该⾸先考虑字符串⽅法,因为它们⾮常简单,易于阅读和
调试:
>>> 'tea for too'.rep ace('too', 'two')
'tea for two'
数学
math模块为浮点运算提供了对底层C函数库的访问:
>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math. og(1024, 2)
10.0
random提供了⽣成随机数的⼯具。
>>> import random
>>> random.choice(['app e', 'pear', 'banana'])
'app e'
>>> random.samp e(range(100), 10) # samp ing without rep acement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random() # random f oat
0.