python基础之五——模块

本博客所有文章仅仅是博主做笔记之用,博客内容并不详细(以后有空会修改完善),思维也有跳跃之处,想详细学习博客内容可参考文章后面的参考链接,祝学习快乐。

本节要点:
1. 定义
2. 导入方法
3. import的本质
4. 导入优化
5. 模块的分类

1.定义

模块:用来从逻辑上组织python代码,本质是一个.py文件

2.导入方法

3.import本质

导入模块的本质就是把.py文件解释一遍
导入包的本质就是执行该包下的_init_.py文件

4.导入优化

import moudle_test
moudle_test.test() #执行1000遍的话需要在moudle_test文件夹下寻找1000遍,耗时间

优化:

from moudle_test import test
test() # 这样不需要每次去找

5.分类

  • 内置模块(标准库)
  • 开源模块
  • 自定义模块

time和datetime

1)时间戳,从1970.01.01到现在的秒数

>>> import time
>>> time.time()
1496627063.7224042   #哈哈,以后玩解密游戏可以考虑加入此元素

2)格式化字符串

>>> time.strftime("%Y-%m-%d  %H:%M:%S",time.localtime())
'2017-06-04  20:28:13'

>>> time.strptime('2017-06-04  20:28:13',"%Y-%m-%d  %H:%M:%S")
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=4, tm_hour=20, tm_min=28, tm_sec=13, tm_wday=6, tm_yday=155, tm_isdst=-1)

3)元组(struct_time)

>>> time.gmtime()
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=4, tm_hour=12, tm_min=8, tm_sec=9, tm_wday=6, tm_yday=155, tm_isdst=0)
>>> time.localtime()
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=4, tm_hour=20, tm_min=8, tm_sec=18, tm_wday=6, tm_yday=155, tm_isdst=0)
>>> time.gmtime(0)   
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
>>> time.gmtime(1234213425)  #将时间戳转化为元组格式
time.struct_time(tm_year=2009, tm_mon=2, tm_mday=9, tm_hour=21, tm_min=3, tm_sec=45, tm_wday=0, tm_yday=40, tm_isdst=0)
>>> a=time.localtime()
>>> time.mktime(a) #将元组格式转化为时间戳
1496578908.0

time.gmtime():结果为UTC时间
time.localtime():结果为UTC+8时区
这里写图片描述

这里写图片描述

random

>>> import random
>>> random.random()   #[0,1) 取不到1
0.6227119560477493  
>>> random.randint(3,8)   #[a,b] 两头都能取到
3
>>> random.randrange(2,5,2) #randrange(start, stop=None, step=1) 可以取到start,取不到stop
2
>>> random.choice([1,2,3,4])  #random.choice(seq) 非空序列随机选择一个元素
3
>>> random.sample({1,2,3,4,4,5,6,7,8,2},2)
[5, 1]     # random.sample(population, k)  总体序列或者集合中随机选择k个不重复的元素
>>> random.uniform(1,2) #指定区间[a,b)中取一个浮点数
1.3309574832594642

>>> x=list(range(10))
>>> random.shuffle(x)   #打乱顺序,注意这个函数的返回值为None,传入的值变了,需要保存原值的话注意备份
>>> x
[5, 1, 7, 3, 2, 0, 4, 9, 6, 8]


>>> x
[5, 1, 7, 3, 2, 0, 4, 9, 6, 8]
>>> p=random.shuffle(x)
>>> p
>>> x
[0, 5, 7, 9, 1, 3, 6, 8, 4, 2]
>>> type(x)
<class 'list'>
>>> 
>>> type(p)
<class 'NoneType'>

os模块

os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
os.curdir  返回当前目录: ('.')
os.pardir  获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2')    可生成多层递归目录
os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()  删除一个文件
os.rename("oldname","newname")  重命名文件/目录
os.stat('path/filename')  获取文件/目录信息
os.sep    输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep    输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep    输出用于分割文件路径的字符串
os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")  运行shell命令,直接显示
os.environ  获取系统环境变量
os.path.abspath(path)  返回path规范化的绝对路径
os.path.split(path)  将path分割成目录和文件名二元组返回
os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path)  返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path)  如果path是绝对路径,返回True
os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间

平时经常遇到需要批量重命名的场景,每次都一个一个的去改名字,学了os模块后写了个简单的批量重命名脚本文件。以下是代码:

import os
def renames(path,new_names):
    """
    批量重命名脚本,path为需要重命名的文件路径,格式为r"C:\python\test"或者"C:\\python\\test"都行。new_names为新名字组成的一个列表或元组
    """
    old_names=os.listdir(path) #获得的文件名会按名称排序,要注意10.txt会在2.txt文件之前
    n=len(old_names)
    for i in range(n):
        print(old_names[i],"------->",new_names[i]+"."+old_names[i].split('.')[-1])

    choice=input("重命名结果如上,你确定吗?(确定:y;退出:n)")

    if choice.strip()=='y':
        for i in range(n):
            os.rename(path+"\\"+old_names[i],path+'\\'+new_names[i]+"."+old_names[i].split('.')[-1])
        print("已完成。")
    else:
        exit("已退出。")

sys模块

方法

    displayhook() -- print an object to the screen, and save it in builtins._
    excepthook() -- print an exception and its traceback to sys.stderr
    exc_info() -- return thread-safe information about the current exception
    exit() -- exit the interpreter by raising SystemExit
    getdlopenflags() -- returns flags to be used for dlopen() calls
    getprofile() -- get the global profiling function
    getrefcount() -- return the reference count for an object (plus one :-)
    getrecursionlimit() -- return the max recursion depth for the interpreter
    getsizeof() -- return the size of an object in bytes
    gettrace() -- get the global debug tracing function
    setcheckinterval() -- control how often the interpreter checks for events
    setdlopenflags() -- set the flags to be used for dlopen() calls
    setprofile() -- set the global profiling function
    setrecursionlimit() -- set the max recursion depth for the interpreter
    settrace() -- set the global debug tracing function

Static objects:

    builtin_module_names -- tuple of module names built into this interpreter
    copyright -- copyright notice pertaining to this interpreter
    exec_prefix -- prefix used to find the machine-specific Python library
    executable -- absolute path of the executable binary of the Python interpreter
    float_info -- a struct sequence with information about the float implementation.
    float_repr_style -- string indicating the style of repr() output for floats
    hash_info -- a struct sequence with information about the hash algorithm.
    hexversion -- version information encoded as a single integer
    implementation -- Python implementation information.
    int_info -- a struct sequence with information about the int implementation.
    maxsize -- the largest supported length of containers.
    maxunicode -- the value of the largest Unicode code point
    platform -- platform identifier
    prefix -- prefix used to find the Python library
    thread_info -- a struct sequence with information about the thread implementation.
    version -- the version of this interpreter as a string
    version_info -- version information as a named tuple
    dllhandle -- [Windows only] integer handle of the Python DLL
    winver -- [Windows only] version number of the Python DLL

json和pickle模块

用于序列化的两个模块

  • json,用于字符串 和 python数据类型间进行转换
  • pickle,用于python特有的类型 和 python的数据类型间进行转换

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

json

encoding:

dumps:  将对象序列化

#coding:utf-8
import json

# 简单编码===========================================
>>> print(json.dumps(['foo',{'bar':('baz', None, 1.0, 2)}]))
#["foo", {"bar": ["baz", null, 1.0, 2]}]

#字典排序
>>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
#{"a": 0, "b": 0, "c": 0}

#自定义分隔符
print(json.dumps([1,2,3,{'4': 5, '6': 7}], sort_keys=True, separators=(',',':')))
# [1,2,3,{"4":5,"6":7}]
print(json.dumps([1,2,3,{'4': 5, '6': 7}], sort_keys=True, separators=('/','-')))
# [1/2/3/{"4"-5/"6"-7}]

#增加缩进,增强可读性,但缩进空格会使数据变大
print(json.dumps({'4': 5, '6': 7}, sort_keys=True,indent=2, separators=(',', ': ')))
# {
#   "4": 5,
#   "6": 7
# }

# 另一个比较有用的dumps参数是skipkeys,默认为False。
# dumps方法存储dict对象时,key必须是str类型,如果出现了其他类型的话,那么会产生TypeError异常,如果开启该参数,设为True的话,会忽略这个key。
data = {'a':1,(1,2):123}
print(json.dumps(data,skipkeys=True))
#{"a": 1}

dump: 将对象序列化并保存到文件

import json
obj = ['foo', {'bar': ('baz', None, 1.0, 2)}]
with open("json.txt","w") as f:
    json.dump(obj,f)

loads:  将序列化字符串反序列化

with open("json.txt") as f:
    data=f.read()
    print(json.loads(data))

load:  将序列化字符串从文件读取并反序列化

with open("json.txt") as f:
    print(json.load(f))

json只支持简单的数据类型,例如我们碰到对象datetime,或者自定义的类对象等json默认不支持的数据类型时,就会出错。

import json,datetime

dt=datetime.datetime.now()
print(dt)

with open("json.txt","w") as f:
    json.dump(dt,f)

TypeError: Object of type ‘datetime’ is not JSON serializable

pickle

python的pickle模块实现了python的所有数据序列和反序列化。基本上功能使用和JSON模块没有太大区别,方法也同样是dumps/dump和loads/load。

与JSON不同的是pickle不是用于多种语言间的数据传输,它仅作为python对象的持久化或者python程序间进行互相传输对象的方法,因此它支持了python所有的数据类型。

dumps

import pickle,datetime

dt=datetime.datetime.now()
print(dt)

with open("json.txt","wb") as f:
    info=pickle.dumps(dt)  #二进制格式文件
    f.write(info)

这不是乱码,pickle存进去的效果就是这样的

dump

import pickle,datetime

dt=datetime.datetime.now()
print(dt)

with open("json.txt","wb") as f:
    pickle.dump(dt,f)

loads

import pickle,datetime

with open("json.txt","rb") as f:
    print(pickle.loads(f.read()))

load

import pickle,datetime

with open("json.txt","rb") as f:
    print(pickle.load(f))

shelve模块

shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式。

import shelve
import datetime
d = shelve.open('shelve_test')  # 打开一个文件

info =  {'age':22,"job":'it'}
name = ["alex", "rain", "test"]
time_now = datetime.datetime.now()

d["name"] = name  # 持久化列表
d["info"] = info  # 持久dict
d['date'] = time_now
d.close()
import shelve
import datetime
d = shelve.open('shelve_test')  # 打开一个文件
print(d.get("name"))
print(d.get("info"))
print(d.get("date"))
d.close()

xml模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单。

xml的格式如下,就是通过<>节点来区别数据结构的:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml:

import xml.etree.ElementTree as ET

tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root.tag)

#遍历xml文档
for child in root:
    print(child.tag, child.attrib)
    for i in child:
        print(i.tag,i.text)

#只遍历year 节点
for node in root.iter('year'):
    print(node.tag,node.text)

修改和删除xml文档内容

import xml.etree.ElementTree as ET

tree = ET.parse("xmltest.xml")
root = tree.getroot()

#修改
for node in root.iter('year'):
    new_year = int(node.text) + 1
    node.text = str(new_year)
    node.set("updated","yes")

tree.write("xmltest.xml")


#删除node
for country in root.findall('country'):
   rank = int(country.find('rank').text)
   if rank > 50:
     root.remove(country)

tree.write('output.xml')

自己创建xml文档

import xml.etree.ElementTree as ET


new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"checked":"no"})
sex = ET.SubElement(name,"sex")
sex.text = '33'
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = '19'

et = ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml", encoding="utf-8",xml_declaration=True)

ET.dump(new_xml) #打印生成的格式

ConfigParser模块

用于生成和修改常见配置文档。

常见格式如下:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

python中生成语法:

import configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9'}

config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'     # 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.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']: print(key)
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'

configparser增删改查语法:

[section1]
k1 = v1
k2:v2

[section2]
k1 = v1

import ConfigParser

config = ConfigParser.ConfigParser()
config.read('i.cfg')

# ########## 读 ##########
#secs = config.sections()
#print secs
#options = config.options('group2')
#print options

#item_list = config.items('group2')
#print item_list

#val = config.get('group1','key')
#val = config.getint('group1','key')

# ########## 改写 ##########
#sec = config.remove_section('group1')
#config.write(open('i.cfg', "w"))

#sec = config.has_section('wupeiqi')
#sec = config.add_section('wupeiqi')
#config.write(open('i.cfg', "w"))


#config.set('group2','k1',11111)
#config.write(open('i.cfg', "w"))

#config.remove_option('group2','age')
#config.write(open('i.cfg', "w"))

hashlib模块

用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

>>> import hashlib
>>> m=hashlib.md5() #一个空的对象,md5换成其他的用法一样
>>> m
<md5 HASH object @ 0x00000234E588C3F0>
>>> m.hexdigest() #显示出来
'd41d8cd98f00b204e9800998ecf8427e'  
>>> hashlib.md5(b"").hexdigest() 
'd41d8cd98f00b204e9800998ecf8427e'  
>>> m.update(b"yang")
>>> m.hexdigest()
'57cb5a26334a6c1d5e27c49def4a0f0d'
>>> m.update(b"hello")  #和上面的值合在一起再求MD5值
>>> m.hexdigest()
'00d2da9375872dc0bd23c1030bd6a2e4'
>>> hashlib.md5(b"yanghello").hexdigest()
'00d2da9375872dc0bd23c1030bd6a2e4'
>>> hashlib.md5("python中文".encode()).hexdigest()
'e9ee79e44a5430955c4baced327b57c4'

re模块

  • match (从头开始匹配)
  • search
  • findall
  • split
  • sub
  • -
'.'     默认匹配除\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'

参考资料

  1. http://www.cnblogs.com/tkqasn/p/6005025.html
  2. http://www.cnblogs.com/wupeiqi/articles/4963027.html
  3. http://www.cnblogs.com/alex3714/articles/5161349.html
  4. http://egon09.blog.51cto.com/9161406/1840425
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章