Python 基础 常用模块

Python 为我们提供了很多功能强大的模块,今天就主要使用的到的模块进行整理,方便后面来翻阅学习。

一、时间模块

    在时间模块中我们重点介绍几种自己常用的功能,主要方便我们按照自己想要的方式获取时间 

  • 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
  • 格式化的时间字符串(Format String)
  • 结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)

    我们先通过Python为我们提供的方法导入时间模块,并且显示一下它们的效果

import time  #导入时间模块

1.时间戳的形式显示时间,通常是用在科学计算上面
print(time.time())#1493279189.2479544 以秒为单位
2.结构化时间:
print(time.localtime()) #本地时区的struct_time
print(time.gmtime())    #UTC时区的struct_time

显示结果:time.struct_time(tm_year=2017, tm_mon=4, tm_mday=27, tm_hour=15, tm_min=50, tm_sec=38, tm_wday=3, tm_yday=117, tm_isdst=0)

3.格式化时间字符串;这种形式就是可以按照我们想要的形式来显示时间
print(time.strftime('%Y-%m-%d %X',time.localtime()))

输出结果为:2017-04-27 15:53:16

    了解了三种时间的表示方式,接下来就有必要对这三者之间的关系进行一下转换:

 1 #--------------------------按图1转换时间
 2 # localtime([secs])
 3 # 将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
 4 time.localtime()
 5 time.localtime(1473525444.037215)
 6 
 7 # gmtime([secs]) 和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。
 8 
 9 # mktime(t) : 将一个struct_time转化为时间戳。
10 print(time.mktime(time.localtime()))#1473525749.0
11 
12 
13 # strftime(format[, t]) : 把一个代表时间的元组或者struct_time(如由time.localtime()和
14 # time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。如果元组中任何一个
15 # 元素越界,ValueError的错误将会被抛出。
16 print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56
17 
18 # time.strptime(string[, format])
19 # 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。
20 print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))
21 #time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,
22 #  tm_wday=3, tm_yday=125, tm_isdst=-1)
23 #在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"。
View Code

1 #--------------------------按图2转换时间
2 # asctime([t]) : 把一个表示时间的元组或者struct_time表示为这种形式:'Sun Jun 20 23:21:05 1993'。
3 # 如果没有参数,将会将time.localtime()作为参数传入。
4 print(time.asctime())#Sun Sep 11 00:43:43 2016
5 
6 # ctime([secs]) : 把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果参数未给或者为
7 # None的时候,将会默认time.time()为参数。它的作用相当于time.asctime(time.localtime(secs))。
8 print(time.ctime())  # Sun Sep 11 00:46:38 2016
9 print(time.ctime(time.time()))  # Sun Sep 11 00:46:38 2016
View Code

对于时间模块了解这些有主要还是要载了解一个“睡觉”函数

import time

time.sleep(3)  # 睡觉3秒钟在执行接下来的代码

二、random 模块(这个模块呢主要是产生随机数的模块)

直接上例子哈!!!

import random
 
print(random.random())#(0,1)----float    大于0且小于1之间的小数
 
print(random.randint(1,3))  #[1,3]    大于等于1且小于等于3之间的整数
 
print(random.randrange(1,3)) #[1,3)    大于等于1且小于3之间的整数
 
print(random.choice([1,'23',[4,5]]))#1或者23或者[4,5]
 
print(random.sample([1,'23',[4,5]],2))#列表元素任意2个组合
 
print(random.uniform(1,3))#大于1小于3的小数,如1.927109612082716 
 
 
item=[1,3,5,7,9]
random.shuffle(item) #打乱item的顺序,相当于"洗牌"
print(item)

还记得登录的时候要输入验证码吗?其实这个东西也没有那没神秘,

import random
def v_code():
    code = ''
    for i in range(5):
        num = random.randint(0,9)
        alf = chr(random.randint(65,90))
        add = random.choice([num,alf]) # 让数字和字母进行随机的选择
        code += str(add)
    return code
print(v_code())

三、os 模块

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下为"	
",Linux下为"
"
os.pathsep    输出用于分割文件路径的字符串 win下为;,Linux下为:
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.path.getsize(path) 返回path的大小

在做比较大的项目的时候,需要把不同的文件放到不同的路劲下面,这在调用的时候就会出现问题,需要对路劲进行修改,以便更好地调用文件,常用的方式主要一下两种:

os路径处理
#方式一:推荐使用
import os
#具体应用
import os,sys
possible_topdir = os.path.normpath(os.path.join(
    os.path.abspath(__file__),
    os.pardir, #上一级
    os.pardir,
    os.pardir
))
sys.path.insert(0,possible_topdir)


#方式二:不推荐使用
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) #此方式添加的路径是临时的

四 、sys模块

1 sys.argv           命令行参数List,第一个元素是程序本身路径
2 sys.exit(n)        退出程序,正常退出时exit(0)
3 sys.version        获取Python解释程序的版本信息
4 sys.maxint         最大的Int值
5 sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
6 sys.platform       返回操作系统平台名称
import sys,time

for i in range(50):
    sys.stdout.write('%s
' %('#'*i))
    sys.stdout.flush()
    time.sleep(0.1)

'''
注意:在pycharm中执行无效,请到命令行中以脚本的方式执行
'''

进度条
View Code

五、shelve模块

shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型

import shelve

f=shelve.open(r'sheve.txt')
# f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']}
# f['stu2_info']={'name':'gangdan','age':53}
# f['school_info']={'website':'http://www.pypy.org','city':'beijing'}

print(f['stu1_info']['hobby'])
f.close()

输出结果为:['piao', 'smoking', 'drinking']

六、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,child.attrib['name'])
    for i in child:
        print(i.tag,i.attrib,i.text)
 
#只遍历year 节点
for node in root.iter('year'):
    print(node.tag,node.text)
#---------------------------------------

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')
    node.set('version','1.0')
tree.write('test.xml')
 
 
#删除node
for country in root.findall('country'):
   rank = int(country.find('rank').text)
   if rank > 50:
     root.remove(country)
 
tree.write('output.xml')
View Code

自己创建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) #打印生成的格式
View Code

七、configparser模块

#!/usr/bin /env python
import configparser
config = configparser.ConfigParser()
config.read('a.txt', encoding='utf-8')
ret = config.sections()                     #获取所有节点名
print(ret)

ret = config.options('test1')               #获取指定节点下的key
print(ret)

ret = config.get('test1', 'k1')               #获取指定节点下的值
print(ret)

has = config.has_section('test1')               #验证是否包含节点
print(has)

has = config.has_section('tttt1')               #验证是否包含节点
print(has)

config.add_section('tttt1')                     #加节点(节点不可以存在)
config.write(open('a.txt', 'w', encoding='utf-8'))

config.remove_section('tttt1')                  #删节点(节点存在)
config.write(open('a.txt', 'w', encoding='utf-8'))

has = config.has_option('tttt1', 'k1')               #验证是否包含节点内的key
print(has)

config.add_option('tttt1', 'k1')                     #加节点内key(节点存在)
config.write(open('a.txt', 'w'))

config.remove_option('tttt1', 'k1')                  #删节点内key(节点存在)
config.write(open('a.txt', 'w'))
View Code

八、logging模块

用于便捷记录日志且线程安全的模块

1、单文件日志

import logging
  
  
logging.basicConfig(filename='log.log',
                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',
                    level=10)
  
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log')

日志等级:

CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

2、多文件日志

对于上述记录日志的功能,只能将日志记录在单文件中,如果想要设置多个日志文件,logging.basicConfig将无法完成,需要自定义文件和日志操作对象。

# 定义文件
file_1_1 = logging.FileHandler('l1_1.log', 'a', encoding='utf-8')
fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s")
file_1_1.setFormatter(fmt)

file_1_2 = logging.FileHandler('l1_2.log', 'a', encoding='utf-8')
fmt = logging.Formatter()
file_1_2.setFormatter(fmt)

# 定义日志
logger1 = logging.Logger('s1', level=logging.ERROR)
logger1.addHandler(file_1_1)
logger1.addHandler(file_1_2)


# 写日志
logger1.critical('1111')

日志一
# 定义文件
file_2_1 = logging.FileHandler('l2_1.log', 'a')
fmt = logging.Formatter()
file_2_1.setFormatter(fmt)

# 定义日志
logger2 = logging.Logger('s2', level=logging.INFO)
logger2.addHandler(file_2_1)

日志(二)

如上述创建的两个日志对象

  • 当使用【logger1】写日志时,会将相应的内容写入 l1_1.log 和 l1_2.log 文件中
  • 当使用【logger2】写日志时,会将相应的内容写入 l2_1.log 文件中

自己写一个可以调用的日志模式:

import logging
def logger():
    logger = logging.getLogger() #创建了一个logger对象
    fh = logging.FileHandler('test')#将日志文件输出到文件内
    ch = logging.StreamHandler() #将日志信息输出到屏幕上
    fm = logging.Formatter('%(asctime)s %(message)s')#写出日志输出的格式
    fh.setFormatter(fm)
    ch.setFormatter(fm)
    logger.addHandler(fh)
    logger.addHandler(ch)
    logger.setLevel('DEBUG')
    return logger


logger =logger()
logger.info([12,34,45,])  #2017-04-24 15:28:29,749 [12, 34, 45]
原文地址:https://www.cnblogs.com/haishiniu123/p/6774995.html