python常用模块及方法

上一篇 / 下一篇  2016-03-01 22:49:43 / 个人分类:python

51Testing软件测试网$q&a#QN ^I{$q
一.sys模块
*sys.path:python的环境变量列表,即执行脚本时,查找的路径列表
例:sys.path.append(os.getcwd()):将当前路径加入到路径列表
    还有一种方法就是,将路径写入到pth文件,并将pth文件放到lib或sitepage目录
*sys.argv[]:参数列表,sys.argv[0]表示脚本本省,1为第一个参数
sys.stdout sys.stdin sys.stderr:输出输入流
 sys.stdout.write('hello') 相当于print

%o2Q/v)E$A1M6L4t e0
二.os模块
os.sep:文件路径分隔符,windows为\\
os.system(filepath);执行可执行文件
os.startfile(filepath):和system等价,但是可以忽略路径中的空格
os.getcwd():获取当前路径
os.chdir():改变当前路径
os.path.dirname():获取文件路径所在目录
os.path.abspath():获取绝对路径
os.listdir():列出目录下的文件以及子目录
os.path.isfile os.path.isdir
例:dirname='a:\temp'
[f for f in os.path.listdir(dirname) is os.path.isfile(os.path.join(dirname,f))]
列出目录下所有文件,不包含子目录
os.path.split():分割目录
例:
>>>os.path.split('d:\\temp\\script\\sample1.py')
['d:\\src\\script',''sample1.py']
>>>os.path.splittest('hello.py')
('hello','.py')
*os.walk(filepath,topdown=true):遍历文件夹下所有子目录
返回3个元组,dirpath路径,dirname:子目录,filename:文件名称,topdown为true代表从顶向底迭代
例:
>>>for dirpath,dirname,filename in os.walk("d:\\temp"):
       for f in filename:
           print os.path.join(dirpath,filename)
 打印文件下的所有文件的完整路径,包括所有子目录下的文件

Un mu;V'S|Q t0

#s#x|:f2t}jA0
三.re模块,正则表达式
re.search('[0-9]','123'):返回matchobject。值为true
re.sub('[a-z]','1',str):将字符串str所有小写字母用1替换
re.groups
>>>phone=re.compile(r'^(\d{3}-(\d{3})-(\d{4})$')
>>>phone.search('123-456-7890').groups()
('123','456','7890')

b~Gv6\ J:I0

f{XU:c1|0
四.time模块
time.sleep(sec):休眠
time.strftime('%Y%m%d%H%M%S'):生成时间戳
如:'20160220102101'
除了time模块还可以使用datetime模块
>>> from datetime import datetime
>>> n=datetime.today()
>>> n.year
2016
51Testing软件测试网'uG8R\m_J W
五.random模块
*random.randrenge(1,101):生成1到101之间的随机数
*random.choice:生成给定序列的随机数
>>> random.choice(string.ascii_letters)
'G'
random.sample():生成指定长度的随机序列
>>> random.sample(string.ascii_lowercase,5)
['v', 'g', 'j', 'l', 'w']

TAG: Python python

 

评分:0

我来说两句

Open Toolbar