Python进阶--常用模块
一、模块、包
什么是模块?
模块实质上就是一个python文件,它是用来组织代码的,意思就是说把python代码写到里面,文件名就是模块的名称,test.py test就是模块名称。
什么是包?
包,package本质就是一个文件夹,和文件夹不一样的是它有一个__init__.py文件,包是从逻辑上来组织模块的,也就是说它是用来存放模块的,如果你想导入其他目录下的模块,那么这个目录必须是一个包才可以导入。
导入模块
import module #导入模块
from module import * #导入该模块中的所有方法,慎用
from module import fun as xx_fun #导入指定的方法,然后起别名
from module import fun1,fun2,fun3 #导入模块下的多个方法
import module,实际上就是把该模块的代码赋值给模块名,也就是module.py里面所有的代码,赋值给了module这个变量,如果是from module import fun,就是把module打开,把module里面的fun方法拿过来使用
导入模块的本质,就是把python文件拿过来执行一次。
使用包中的模块需要在__init__.py文件中from . import xxx
模块分类:
标准库:python内置的
开源模块:第三方
自定义模块:自己写的
二、os、sys模块
import os
print(os.getcwd())#取当前工作目录
os.chmod("/usr/local",7)#给文件/目录加权限
print(os.chdir("../"))#更改当前目录
print(os.curdir)#当前目录
print(os.pardir)#父目录
print(os.makedirs("/usr/hehe/hehe1"))#递归创建文件夹,父目录不存在时创建父目录
print(os.removedirs("/usr/hehe/hehe1"))#递归删除空目录
print(os.mkdir("test1"))#创建文件夹
print(os.rmdir("test1"))#删除指定的文件夹
print(os.remove("test"))#删除文件
print(os.listdir('.'))#列出一个目录下的所有文件
os.rename("test","test1")#重命名
print(os.stat("len_os.py"))#获取文件信息
print(os.sep)#当前操作系统的路径分隔符
print(os.linesep)#当前操作系统的换行符
print(os.pathsep)#当前系统的环境变量中每个路径的分隔符,linux是:,windows是;
print(os.environ)#当前系统的环境变量
print(os.name)#当前系统名称
print(os.system)#执行操作系统命令
print(os.path.abspath(__file__))#获取绝对路径
print(os.path.split("/usr/hehe/hehe.txt"))#分割路径和文件名
print(os.path.dirname("/usr/local"))#获取父目录
print(os.path.basename("/usr/local"))#获取最后一级,如果是文件显示文件名,如果是目录显示目录名
print(os.path.exists("/usr/local"))#目录/文件是否存在
print(os.path.isabs("."))#判断是否是绝对路径
print(os.path.isfile("/usr/local"))#判断是否是一个文件
print(os.path.isdir("/usr/local"))#是否是一个路径
print(os.path.join("/root",'hehe','a.sql'))#拼接成一个路径
print(os.path.getatime("len_os.py"))#输出最近访问时间
print(os.path.getmtime("len_os.py"))#输出最近访问时间
sys.argv 命令行参数List,第一个元素是程序本身路径
sys.exit(n) 退出程序,正常退出时exit(0)
sys.version 获取Python解释程序的版本信息
sys.maxint 最大的Int值
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform 返回操作系统平台名称
sys.stdout.write('please:')#向屏幕输出一句话
val = sys.stdin.readline()[:-1]#获取输入的值
三、random模块
import random,string
print(random.random())#随机浮点数,默认取0-1,不能指定范围
print(random.randint(1,20))#随机整数
print(random.randrange(1,20))#随机产生一个range
print(random.choice('x23serw4'))#随机取一个元素
print(random.sample('hello',2))#从序列中随机取几个元素
print(random.uniform(1,9))#随机取浮点数,可以指定范围
x = [1,2,3,4,6,7]
random.shuffle(x)#洗牌,打乱顺序,会改变原list的值
print(x)
print(string.ascii_letters+string.digits)#所有的数字和字母
四、time&datetime模块
time和datetime模块主要用于操作时间
时间有三种表示方式,一种是时间戳、一种是格式化时间、一种是时间元组
import datetime,time
print(time.timezone)#和标准时间相差的时间,单位是s
print(time.time())#获取当前时间戳
print(time.sleep(1))#休息几s
print(time.gmtime())#把时间戳转换成时间元组,如果不传的话,默认取标准时区的时间戳
print(time.localtime())#把时间戳转换成时间元组,如果不传的话,默认取当前时区的时间戳
print(time.mktime(time.localtime()))#把时间元组转换成时间戳
print(time.strftime("%y%m%d %H%M%S"))#将时间元组转换成格式化输出的字符串
print(time.strptime("20160204 191919","%Y%m%d %H%M%S"))#将格式化的时间转换成时间元组
print(time.struct_time)#时间元组
print(time.asctime())#时间元转换成格式化时间
print(time.ctime())#时间戳转换成格式化时间
print(datetime.datetime.now())#当然时间格式化输出
print(datetime.datetime.now()+datetime.timedelta(3))#3天后的时间
print(datetime.datetime.now()+datetime.timedelta(-3))#3天前的时间
五、shelve模块
shelve模块用来持久化存储数据,比起json来,json只能存储list、字典这样的数据类型,如果是一个函数,一个类的话,就没有办法存储了,但是shelve模块可以,shelve模块是key-value存储的,value是你存储的内容,使用如下:
import shelve
d = shelve.open('shelve_test') #打开一个文件
class Test(object):
def __init__(self,n):
self.n = n
t = Test(123)
t2 = Test(123334)
def func():
print('hello')
name = ["alex","rain","test"]
d["test"] = name #持久化列表
d["t1"] = t #持久化类
d["t2"] = t2
d["t3"] = func
print(d.get("t3"))#获取内容
d.close()
六、hashlib模块
hashlib模块,主要用于加密相关的操作,在python3的版本里,代替了md5和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法。
import hashlib m = hashlib.md5()
m.update(b"Hello")
m.update(b"It's me")
print(m.digest())
m.update(b"It's been a long time since last time we ...") print(m.digest()) #2进制格式hash
print(len(m.hexdigest())) #16进制格式hash
# ######## md5 ######## hash = hashlib.md5()
hash.update('admin')
print(hash.hexdigest())
# ######## sha1 ######## hash = hashlib.sha1()
hash.update('admin')
print(hash.hexdigest())
# ######## sha256 ######## hash = hashlib.sha256()
hash.update('admin')
print(hash.hexdigest()) # ######## sha384 ######## hash = hashlib.sha384()
hash.update('admin')
print(hash.hexdigest())
# ######## sha512 ######## hash = hashlib.sha512()
hash.update('admin')
print(hash.hexdigest())
七、configparser模块
configparser模块用来操作配置文件,用于生成和修改常见配置文档,python 3.x 中为configparser,python2中为ConfigParser。
一个常见的配置文件如下:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes [bitbucket.org]
User = hg [topsecret.server.com]
Port = 50022
ForwardX11 = no
import configparser config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '',
'Compression': 'yes',
'CompressionLevel': ''} config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile)
下面是一些常用的操作,修改、添加、删除节点、属性
import configparser
config = configparser.ConfigParser()
config.read('my.cnf')
sections = config.sections()#获取所有节点
print(config.get('bitbucket.org','User'))#取对应节点下面key的值
config.add_section('NEW')#增加节点
config.set('NEW','test','true')#增加节点下面对应的熟悉和值
config.set('DEFAULT','niu','')#修改节点下的属性
config.write(open("my.cnf","w"))#写入修改后的文件
config.has_option('NEW','test')#节点下是否有对应的属性
config.has_section('NEW')#是否有该节点
config.remove_section('NEW')#删除节点
config.remove_option('NEW','test')#删除节点下面的key
八、re模块
re模块是正则表达式模块,用来匹配一些特定的字符串。
常用的正则表达式符号
'.' 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
'^' 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)
'$' 匹配字符结尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以
'*' 匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 结果为['abb', 'ab', 'a']
'+' 匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb']
'?' 匹配前一个字符1次或0次
'{m}' 匹配前一个字符m次
'{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb']
'|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC'
'(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c
'\A' 只从字符开头匹配,re.search("\Aabc","alexabc") 是匹配不到的
'\Z' 匹配字符结尾,同$
'\d' 匹配数字0-9
'\D' 匹配非数字
'\w' 匹配[A-Za-z0-9]
'\W' 匹配非[A-Za-z0-9]
's' 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 结果 '\t'
常用的匹配语法
re.match 从头开始匹配
re.search 匹配包含
re.findall 把所有匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符当做列表分隔符
re.sub 匹配字符并替换
Python进阶--常用模块的更多相关文章
- python的常用模块之collections模块
python的常用模块之collections模块 python全栈开发,模块,collections 认识模块 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文 ...
- Python进阶----pymysql模块的使用,单表查询
Python进阶----pymysql模块的使用,单表查询 一丶使用pymysql 1.下载pymysql包: pip3 install pymysql 2.编写代码 ...
- Python进阶(八)----模块,import , from import 和 `__name__`的使用
Python进阶(八)----模块,import , from import 和 __name__的使用 一丶模块的初识 #### 什么是模块: # 模块就是一个py文件(这个模块存放很多相似的功能, ...
- Python进阶之模块
在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就相对较少,很 ...
- python之常用模块
python 常用模块 之 (subprocess模块.logging模块.re模块) python 常用模块 之 (序列化模块.XML模块.configparse模块.hashlib模块) pyth ...
- python之常用模块二(hashlib logging configparser)
摘要:hashlib ***** logging ***** configparser * 一.hashlib模块 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 摘要算法 ...
- Python学习——python的常用模块
模块:用一堆代码实现了某个功能的代码集合,模块是不带 .py 扩展的另外一个 Python 文件的文件名. 一.time & datetime模块 import time import dat ...
- python 之常用模块
一 认识模块 二 常用模块 (1)re模块 (2)collections模块 一 认识模块 (1)什么是模块 (2)模块的导入和使用 (1)模块是:一个模块就是一个包含 ...
- Python之常用模块--collections模块
认识模块 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用python编写的 ...
随机推荐
- Maximum execution time of 30 seconds exceeded解决错误方法
Maximum execution time of 30 seconds exceeded解决错误方法Fatal error: Maximum execution time of 30 seconds ...
- linux服务器文件索引inodes满了
inode节点中,记录了文件的类型.大小.权限.所有者.文件连接的数目.创建时间与更新时间等重要的信息,还有一个比较重要的内容就是指向数据块的指针.一般情况不需要特殊配置,如果存放文件很多,需要配置. ...
- Sybase 存储过程中IF的用法
Sybase 存储过程中IF的用法 --@i_val 为参数 or @i_val is null then begin --执行内容 end; end if;
- C_Learning (1)
/数据类型及占用字节 char 1个字节{-128~127} int 2.4个字节,取决于平台是16位还是32位机子{-65536~65535} short int 2个字节{-32768 ...
- 托管C++调用C#
拿到了一个第三方demo,有dll,有.cpp..h,打开解决方案,如下图: 网上资料貌似很少,根据猜测: 这是使用托管C++来调用C#的方式. 过程: 1.先使用C#代码实现界面和功能,其实就是一个 ...
- Python3基础 try-except-finally 的简单示例
Python : 3.7.0 OS : Ubuntu 18.04.1 LTS IDE : PyCharm 2018.2.4 Conda ...
- mips32和x86下的大小端模式判定
一.背景 1.1 mips32搭载32bit vxworks操作系统 1.2 x86搭载64bit windows10操作系统 二.大小端模式判定前的准备 2.1 先要知道各种架构上各种整型数占据的b ...
- Mato的文件管理 (莫队)题解
思路: 莫队模板题,转换几次就是找逆序数,用树状数组来储存数就行了 注意要离散化 代码: #include<queue> #include<cstring> #include& ...
- ZooKeeper与Kafka相关
Kafka集群搭建: https://www.cnblogs.com/likehua/p/3999538.html https://www.cnblogs.com/mikeguan/p/7079013 ...
- 【第五章】 springboot + mybatis
springboot集成了springJDBC与JPA,但是没有集成mybatis,所以想要使用mybatis就要自己去集成.集成方式相当简单. 1.项目结构 2.pom.xml <!-- 与数 ...