python内置模块

subprocess模块是对

  • os.system
  • os.spawn*
    以上这两个的替换,以后尽量使用subprocess,这两个会逐步淘汰

  • os.system 输出命令结果到屏幕,返回命令执行状态(0成功)
  • os.popen("dir") 保存命令执行结果,无执行状态
  • os.popen("dir").read()读取命令结果

subprocess

  • subprocess.run('命令','参数1','参数2','参数3'...)
    执行命令

  • subprocess.run('命令1|命令2',shell = True)
    直接让linux自己解析命令(用于带管道符|的命令)

执行命令,返回命令执行状态 , 0 or 非0

>>> retcode = subprocess.call(["ls", "-l"])

执行命令,如果命令结果为0,就正常返回,否则抛异常

>>> subprocess.check_call(["ls", "-l"])
0

接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果

>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')

接收字符串格式命令,并返回结果

>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'

执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res

>>> res=subprocess.check_output(['ls','-l'])
>>> res**#执行命令,返回命令执行状态 , 0 or 非0**
>>> retcode = subprocess.call(["ls", "-l"])

执行命令,如果命令结果为0,就正常返回,否则抛异常

>>> subprocess.check_call(["ls", "-l"])
0

**接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果 **

>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')

接收字符串格式命令,并返回结果**

>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'

执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res**

>>> res=subprocess.check_output(['ls','-l'])
>>> res
b'total 0 drwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM '

上面那些方法,底层都是封装的subprocess.Popen

poll()
Check if child process has terminated. Returns returncode
检查命令是否执行完毕,None未完成,0完成、例“res.poll()

wait()
Wait for child process to terminate. Returns returncode attribute.
等待命令是行完毕返回结果,0完成、例“res.wait()

terminate() 杀掉所启动进程
communicate() 等待任务结束

stdin 标准输入

stdout 标准输出

stderr 标准错误

pid
The process ID of the child process.

例子

>>> p = subprocess.Popen("df -h|grep disk",stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
>>> p.stdout.read()
b'/dev/disk1 465Gi 64Gi 400Gi 14% 16901472 104938142 14% / 'b'total 0 drwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM '


re模块

'.'     默认匹配除
之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
'^'     匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","
abc
eee",flags=re.MULTILINE)
'$'     匹配字符结尾,或e.search("foo$","bfoo
sdfsf",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") 是匹配不到的
''    匹配字符结尾,同$
'd'    匹配数字0-9
'D'    匹配非数字
'w'    匹配[A-Za-z0-9]
'W'    匹配非[A-Za-z0-9]
's'     匹配空白字符、	、
、
 , re.search("s+","ab	c1
3").group() 结果 '	'
 
'(?P<name>...)' 分组匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 结果{'province': '3714', 'city': '81', 'birthday': '1993'}

logging模块

  • 很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug(), info(), warning(), error() and critical() 5个级别,下面我们看一下怎么用。

最简单用法

import logging

logging.warning("user [alex] attempted wrong password more than 3 times")
logging.critical("server is down")

#屏幕输出
WARNING:root:user [alex] attempted wrong password more than 3 times
CRITICAL:root:server is down

写入日志文件

import logging

logging.basicConfig(filename='app.log',
                    format='%(asctime)s %(filename)s line:%(lineno)d [%(levelname)s] %(message)s',
                    datefmt='%Y-%m-%d %I:%M:%S %p')

logging.debug('debug inf')
logging.info('info log...')
logging.warning("user [alex] attempted wrong password more than 3 times")
logging.error('err inf')
logging.critical("server is down")
---------
在log文件中显示为:
2017-06-24 07:43:14 PM loggingģ_module.py line:11 [WARNING] user [alex] attempted wrong password more than 3 times
2017-06-24 07:43:14 PM loggingģ_module.py line:12 [ERROR] err inf
2017-06-24 07:43:14 PM loggingģ_module.py line:13 [CRITICAL] server is down
  • 如果想同时把log打印在屏幕和文件日志里,就需要了解一点复杂的知识 了

Python 使用logging模块记录日志涉及四个主要类,使用官方文档中的概括最为合适:

  • logger提供了应用程序可以直接使用的接口;
  • handler将(logger创建的)日志记录发送到合适的目的输出;
  • filter提供了细度设备来决定输出哪条日志记录;
  • formatter决定日志记录的最终输出格式。

logger

  • 每个程序在输出信息之前都要获得一个Logger。Logger通常对应了程序的模块名,比如聊天工具的图形界面模块可以这样获得它的Logger:

  • LOG=logging.getLogger(”chat.gui”)

  • 而核心模块可以这样:

  • LOG=logging.getLogger(”chat.kernel”)

  • Logger.setLevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高

  • Logger.addFilter(filt)、Logger.removeFilter(filt):添加或删除指定的filter

  • Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或删除指定的handler

  • Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():可以设置的日志级别

handler

  • handler对象负责发送相关的信息到指定目的地。Python的日志系统有多种Handler可以使用。有些Handler可以把信息输出到控制台,有些Logger可以把信息输出到文件,还有些 Handler可以把信息发送到网络上。如果觉得不够用,还可以编写自己的Handler。可以通过addHandler()方法添加多个多handler
  • Handler.setLevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略
  • Handler.setFormatter():给这个handler选择一个格式
  • Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一个filter对象

每个Logger可以附加多个Handler。接下来我们就来介绍一些常用的Handler:

1) logging.StreamHandler输出到屏幕

使用这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息。它的构造函数是:
StreamHandler([strm])
其中strm参数是一个文件对象。默认是sys.stderr

2) logging.FileHandler

和StreamHandler类似,用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文件。它的构造函数是:
FileHandler(filename[,mode])
filename是文件名,必须指定一个文件名。
mode是文件的打开方式。参见Python内置函数open()的用法。默认是’a',即添加到文件末尾。

3) logging.handlers.RotatingFileHandler

这个Handler类似于上面的FileHandler,但是它可以管理文件大小。当文件达到一定大小之后,它会自动将当前日志文件改名,然后创建 一个新的同名日志文件继续输出。比如日志文件是chat.log。当chat.log达到指定的大小之后,RotatingFileHandler自动把 文件改名为chat.log.1。不过,如果chat.log.1已经存在,会先把chat.log.1重命名为chat.log.2。。。最后重新创建 chat.log,继续输出日志信息。它的构造函数是:
RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
其中filename和mode两个参数和FileHandler一样。
maxBytes用于指定日志文件的最大文件大小。如果maxBytes为0,意味着日志文件可以无限大,这时上面描述的重命名过程就不会发生。
backupCount用于指定保留的备份文件的个数。比如,如果指定为2,当上面描述的重命名过程发生时,原有的chat.log.2并不会被更名,而是被删除。

4) logging.handlers.TimedRotatingFileHandler

这个Handler和RotatingFileHandler类似,不过,它没有通过判断文件大小来决定何时重新创建日志文件,而是间隔一定时间就自动创建新的日志文件。重命名的过程与RotatingFileHandler类似,不过新的文件不是附加数字,而是当前时间。它的构造函数是:
TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
其中filename参数和backupCount参数和RotatingFileHandler具有相同的意义。
interval是时间间隔。
when参数是一个字符串。表示时间间隔的单位,不区分大小写。它有以下取值:
S 秒
M 分
H 小时
D 天
W 每星期(interval==0时代表星期一)
midnight 每天凌晨

一个简单的日志输出模块

import logging
# 创建logger
def logging_obj():
    logger = logging.getLogger('TEST-LOG')
    logger.setLevel(logging.DEBUG)#设置屏幕输出log级别为debug
    # 创建屏幕输出的handler
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    # 创建文件输出的handler
    fh = logging.FileHandler("access.log")
    fh.setLevel(logging.WARNING)#设置文件输出log级别为warning
    # 创建格式
    formatter = logging.Formatter('%(asctime)s %(filename)s line:%(lineno)d [%(levelname)s] %(message)s')
    formatter.datefmt = '%Y-%m-%d %I:%M:%S %p'#更改时间格式
    # 添加输出格式
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
    # 添加handler输出源
    logger.addHandler(ch)
    logger.addHandler(fh)
    return logger
#调用
logger = logging_obj()
logger.warning('warning msg...')
logger.debug('debug msg...')

hashlib模块

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
'''
def digest(self, *args, **kwargs): # real signature unknown
    """ Return the digest value as a string of binary data. """
    pass
 
def hexdigest(self, *args, **kwargs): # real signature unknown
    """ Return the digest value as a string of hexadecimal digits. """
    pass
 
'''
import hashlib
 
# ######## 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())

python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密

散列消息鉴别码,简称HMAC,是一种基于消息鉴别码MAC(Message Authentication Code)的鉴别机制。使用HMAC时,消息通讯的双方,通过验证消息中加入的鉴别密钥K来鉴别消息的真伪;

一般用于网络通信中消息加密,前提是双方先要约定好key,就像接头暗号一样,然后消息发送把用key把消息加密,接收方用key + 消息明文再加密,拿加密后的值 跟 发送者的相对比是否相等,这样就能验证消息的真实性,及发送者的合法性了。

import hmac
h = hmac.new('天王盖地虎'.encode('utf-8'),'宝塔镇河妖'.encode('utf-8'))
print(h.hexdigest())

注意hashlib 模块和hmac处理中文需要先endcode


ConfigParser配置文件模块

配置文件示例

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no

创建config文件

import configparser
#生成config文件
config = configparser.ConfigParser()#创建ConfigParser对象
config['bitbucket.org'] = {} #创建节点
config['bitbucket.org']['User'] = 'hg'#节点下的值
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
#config['topsecret.server.com']['Host Port'] = '50022' 也可以
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)

读取config文件

config = configparser.ConfigParser()
config.read('config.ini')
print(config.sections())
print(config['DEFAULT']['CompressionLevel'])
for tag in config:
    print(tag)
for key in config['DEFAULT']:
    print(key,':',config['DEFAULT'][key])

改config文件

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"))

xlm处理模块

  • xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。

示例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文档

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") #根节点
person_info = ET.SubElement(new_xml, "person_info", attrib={"enrolled": "yes"})#namelist的子节点
name = ET.SubElement(person_info, "name")
name.text = 'lmc'
age = ET.SubElement(person_info, "age", attrib={"checked": "no"})#name的子节点
sex = ET.SubElement(person_info, "sex")#name的子节点
sex.text = 'man'
age.text = '28'#age标签之间的值
person_info2 = ET.SubElement(new_xml, "person_info", attrib={"enrolled": "no"})
name2 = ET.SubElement(person_info2, "name")
name2.text = 'wly'
age = ET.SubElement(person_info2, "age")
age.text = '19'

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

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

shelve模块

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

import shelve
#--------创建shelve对象持久化数据-----
d = shelve.open('shelve_test')#获取shelve对象
info = {'age':22,'job':'银行'}
name = ['lmc','wly','lqy']
d['name'] = name #持久化列表
d['info'] = info #持久化dict
d.close()
#读取shelve数据
d = shelve.open('shelve_test')
print(d.get('name'))
print(d.get('info'))
d.close() #关闭shelve对象
#遍历所有数据
for item in sh.items():
    print('键[{}] = 值[{}]'.format(item[0], sh[item[0]]))
#删除shelve对象中的某个键值对
del sh['d']

shutil 用于高级的 文件、文件夹、压缩包 处理


shutil.copyfileobj(fsrc, fdst[, length])

  • 将文件内容拷贝到另一个文件中,可以部分内容
  • 源代码
def copyfileobj(fsrc, fdst, length=16*1024):
    """copy data from file-like object fsrc to file-like object fdst"""
    while 1:
        buf = fsrc.read(length)
        if not buf:
            break
        fdst.write(buf)
  • 从一个文件对象拷贝到另一个文件对象
import shutil
f1 = open('test',encoding='utf-8')
f2 = open('test','w',encoding='utf-8')
shutil.copyfileobj(f1,f2)

shutil.copyfile(src, dst)

  • 拷贝文件
  • 例:shutil.copyfile('原文件', '新文件')

shutil.copymode(src, dst)

  • 仅拷贝权限。内容、组、用户均不变
  • 仅复制权限,不copy文件
  • shutil.copymode(文件1, 文件2)
  • 把文件1的权限拷贝给文件2,两个文件都必须存在

shutil.copystat(src, dst)

  • 拷贝状态的信息,包括:mode bits, atime, mtime, flags
  • 仅复制权限,不copy文件
  • shutil.copymode(文件1, 文件2)
  • 把文件1的权限拷贝给文件2,两个文件都必须存在

shutil.copy(src, dst)

  • 拷贝文件和权限

shutil.copy2(src, dst)

  • 拷贝文件和状态信息

shutil.copytree(src, dst, symlinks=False, ignore=None)

  • 递归的去拷贝文件
  • 例如:copytree(source, destination, ignore=ignore_patterns('.pyc', 'tmp'))

shutil.rmtree(path[, ignore_errors[, onerror]])

shutil.move(src, dst)

shutil.make_archive(base_name, format,...)

  • 创建压缩包并返回文件路径,例如:zip、tar

  • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,如:package_name=>保存至当前路径

  • 如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/

  • format:压缩包种类,“zip”, “tar”, “bztar”,“gztar”

  • root_dir:要压缩的文件夹路径(默认当前目录)

  • owner:用户,默认当前用户

  • group:组,默认当前组

  • logger:用于记录日志,通常是logging.Logger对象

#将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
import shutil
ret = shutil.make_archive("wwwwwwwwww",'gztar',root_dir='/Users/wupeiqi/Downloads/test')
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
import shutil
ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww",'gztar',root_dir='/Users/wupeiqi/Downloads/test')


shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:

zipfile模块

import zipfile
# 压缩
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log')
z.write('data.data')
z.close()

# 解压
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall()
z.close()

tarfile模块

import tarfile
# 压缩
tar = tarfile.open('your.tar','w')
tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip')
tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip')
tar.close()

# 解压
tar = tarfile.open('your.tar','r')
tar.extractall()  # 可设置解压地址
tar.close()

sys模块

sys.argv

  • 命令行参数List,第一个元素是程序本身路径
  • 例:假设有一个脚本c:a.py
    在命令行输入c:a.py 1 2 3 4
    脚本内有sys.argv则会获取一个参数列表
    ['a.py','1','2','3','4']

sys.exit(n)

  • 退出程序,正常退出时exit(0)

sys.version

  • 获取Python解释程序的版本信息

sys.path

  • 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

sys.platform

  • 返回操作系统平台名称

sys.stdout.write('please:')

val = sys.stdin.readline()[:-1]


import os


os.getcwd()

  • 获取当前工作目录

os.chdir("dirname")

  • 改变当前脚本工作目录;相当于shell下cd

注意:

  • 路径需要\转义,即:c:\123\456
  • 也可以使用r"c:123456"

os.curdir

  • 返回当前目录: ('.')

os.pardir

  • 获取当前目录的父目录字符串名:('..')

os.makedirs('dirname1/dirname2')

  • 可生成多层递归目录
  • 即:父级目录dirname1不存在也会正常创建(递归创建)

os.removedirs('dirname1')

  • 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推

os.mkdir('dirname')

  • 生成单级目录;相当于shell中mkdir dirname
  • 如果dirname的父级目录不存在,报错

os.rmdir('dirname')

  • 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname

os.listdir('dirname')

  • 返回目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印所有文件和子目录,包括隐藏文件,并以列表方式打印

os.remove()

  • 删除一个文件

os.rename('原名','新名')

  • 重命名文件/目录

os.stat('path/filename')

  • 获取文件/目录信息

os.sep

  • 输出操作系统特定的路径分隔符,win下为"",Linux下为"/"

os.linesep

  • 输出当前平台使用的行终止符,win下为" ",Linux下为" "

os.pathsep

  • 输出用于分割文件路径的字符串,win下为";",linux下为':'

os.name

  • 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'

os.environ

  • 返回系统环境变量字典

os.system('bash command')

  • 运行shell命令,直接显示
  • 例:os.system('ipconfig /all')

os.path 功能


os.path.abspath(path)

  • 返回path规范化的绝对路径
  • 例:os.path.abspath(__file__)

os.path.split(path)

  • 将path分割为目录和文件的二元素元组,这个path可以不存在
  • 例:os.path.split(r'c:aa.txt')
  • 返回('c:\a\b','a.txt')

os.path.dirname(path)

  • 返回目录名,这个path可以不存在
  • 例:os.path.dirname(r'c:aa.txt')
  • 返回c:\a\b

os.bath.basename(path)

  • 返回文件名,这个path可以不存在
    -例:os.path.basename(r'c:aa.txt')
  • 返回a.txt

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所指向的文件或者目录的最后修改时间
  • 返回的是一个时间戳

import random


random.random()

  • 用于产生0到1之间的随机浮点数

random.randint(1,3)

  • random.randint(a,b)用于产生一个随机数n,a<=n<=b

random.randrange(a,b,step)

  • random.randrange的函数原型为:random.randrange([start], stop[, step]),

  • 从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),
  • 结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。
  • random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。

random.choice()

  • random.choice从序列中获取一个随机元素。random.choice从序列中获取一个随机元素。
  • 其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。
  • 这里要说明一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。
  • list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章。
  • 下面是使用choice的一些例子:
print(random.choice("学习Python"))#学
print(random.choice(["JGood","is","a","handsome","boy"]))  #List
print(random.choice(("Tuple","List","Dict")))   #List
print(random.sample(["1","2","3","4","5"],3))    #[1, 2, 5]
#random.sample(序列,要取得长度/个数)
#random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。

一些应用

# encoding: utf-8
import random
import string
#随机整数:
print( random.randint(0,99))  #70
 
#随机选取0到100间的偶数:
print(random.randrange(0, 101, 2)) #4
 
#随机浮点数:
print( random.random()) #0.2746445568079129
print(random.uniform(1, 10)) #9.887001463194844
 
#随机字符:
print(random.choice('abcdefg&#%^*f')) #f
 
#多个字符中选取特定数量的字符:
print(random.sample('abcdefghij',3)) #['f', 'h', 'd']
 
#随机选取字符串:
print( random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )) #apple
#洗牌#
items = [1,2,3,4,5,6,7]
print(items) #[1, 2, 3, 4, 5, 6, 7]
random.shuffle(items)
print(items) #[1, 4, 7, 2, 5, 3, 6]


生成随机验证码

import random
checkcode = ''
for i in range(6):
    current = random.randrange(0,6) 
    #产生一个预先用来判断产生的是字母或数字的随机数
    if current != i:
        current = chr(random.randint(65,90))
        #如果随机数=i,则产生一个大写字母(65~90表示ASCII的大写字母,97~122表示小写字母)
    else:#否则产生一个0~9随机整数
        current = random.randint(0,9)
    checkcode += str(current)#组合验证码
print(checkcode)

使用json需要引入模块

import json

  • 代码示例:
a={
    'name':'lmc',
    'age':28
}
#json to str 序列化
with open('test.text','w') as f:
    f.write(str(a))
    f.write(json.dumps(a))
#str to json 反序列化
with open('test.text','r') as f:
    data = json.loads(f.read())
    print(data['age'])
  • json只能处理简单数据,例如字典,列表等。用于不同语言程序之间的交互

使用pickle需要引入模块

import pickle

  • 可以序列化复杂的数据,如函数。用法和json一样
  • json和pickle的简化用法
with open('test.text','w') as f:
    json.dump(data,f)

with open('test.text','r') as f:
    data = json.load(f)

shelve模块

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

import shelve
#--------创建shelve对象持久化数据-----
d = shelve.open('shelve_test')#获取shelve对象
info = {'age':22,'job':'银行'}
name = ['lmc','wly','lqy']
d['name'] = name #持久化列表
d['info'] = info #持久化dict
d.close()
#读取shelve数据
d = shelve.open('shelve_test')
print(d.get('name'))
print(d.get('info'))
d.close() #关闭shelve对象
#遍历所有数据
for item in sh.items():
    print('键[{}] = 值[{}]'.format(item[0], sh[item[0]]))
#删除shelve对象中的某个键值对
del sh['d']
原文地址:https://www.cnblogs.com/limich/p/7476945.html