python内置模块(random、os、sys、shelve、configparser、xml)
欢迎关注博主 Mindtechnist 或加入【Linux C/C++/Python社区】一起探讨和分享Linux C/C++/Python/Shell编程、机器人技术、机器学习、机器视觉、嵌入式AI相关领域的知识和技术。
专栏:《python从入门到实战》
random模块 – 随机模块
import random
导入模块
print(random.random())
获取(0,1)之间的浮点数float
print(random.randint(1,3))
[1,3] – int整形
print(random.randrange(1,3))
[1,3) – int
print(random.choice([1,'23',[4,5]]))
随机获取列表中的一个值
print(random.sample([1,'23',[4,5]],2))
随机在列表中获取两个值,组成一个列表
print(random.uniform(1,3))
1.927109612082716 – 自定范围内的浮点型
打乱顺序
item=[1,3,5,7,9]
random.shuffle(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)) #随机字母-ascii码ret=random.choice([num,alf])code += str(ret)return codeprint(v_code())
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下为"\\r\\n",Linux下为"\\n"
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[, ...]])
将多个路径组合后返回,第一个绝对路径之前的参数将被忽略,在Windows和Linux下都可以用,跨平台
os.path.getatime(path)
返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path)
返回path所指向的文件或者目录的最后修改时间
sys模块
sys.argv
命令行参数List,第一个元素是程序本身路径
sys.exit(n)
退出程序,正常退出时exit(0)
sys.version
获取Python解释程序的版本信息
sys.maxint
最大的Int值
sys.path
返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform
返回操作系统平台名称
示例:实现进度条
import sys,time
for i in range(10):sys.stdout.write('#')time.sleep(1)sys.stdout.flush() #不加这句话,默认会等全部写完最后一块打印出来
shelve模块
只有一个open函数,返回类似字典的对象,可读可写。key必须为字符串,而值可以是python所支持的数据类型,不支持跨语言。
示例:
import shelvef = shelve.open(r'shelve.txt') #文件后缀毫无意义,它只是给人看的f['stu1_info']={'name':'alex','age':'18'}
f['stu2_info']={'name':'alvin','age':'20'}
f['school_info']={'website':'oldboyedu.com','city':'beijing'}
# 会生成三个文件 .bak .dat .dir,文件内容是不可读的
print(f.get('stu_info')['age'])
f.close()
configparser模块 – 配置文件解析模块
生成一个配置文件,配置文件本质就是一个字典。文件格式是固定的,每个大的字典是一个块,[ ]是自动加上的。
import configparserconfig = configparser.ConfigParser() #创建这个对象相当于得到一个空字典config={}
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'<br>
with open('example.ini', 'w') as configfile: #把对象写到磁盘文件中config.write(configfile) #用要写入对象的write方法,而不是文件句柄
xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单。特别是在金融领域广泛使用。
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>
python中操作xml文件
import xml.etree.ElementTree as ET
#把xml.etree.ElementTree简写为ET,as表示简写tree = ET.parse("xmltest.xml") #解析xml数据,返回一个对象 – 树
root = tree.getroot() #获取根节点 – 根对象
print(root.tag) #打印根标签名字
#<country name="Liechtenstein">
#标签名是country,后面的键值对都是标签的属性 {属性名=属性值}#遍历xml文档
for child in root:print(child.tag, child.attrib) #打印标签名字、属性,没有属性打印{}for i in child:print(i.tag,i.text) #打印标签的内容text,没有打印None#只遍历year 节点
for node in root.iter('year'): #node是每一个year标签,从root中找print(node.tag,node.text)
#---------------------------------------import xml.etree.ElementTree as ETtree = ET.parse("xmltest.xml")
root = tree.getroot()#修改
for node in root.iter('year'):new_year = int(node.text) + 1node.text = str(new_year) #设置标签内容node.set("updated","yes") #设置一个标签属性 updated = yes#上面的操作只是把内存中的数据改了,但是还没有写入磁盘文件
tree.write("xmltest.xml") #写入磁盘文件
#覆盖原来的文件(同名)或保存一个新文件(不同名)#删除node
for country in root.findall('country'): #findall可以查找多个标签rank = int(country.find('rank').text)if rank > 50:root.remove(country)tree.write('output.xml')
使用python创建xml文档
import xml.etree.ElementTree as ETnew_xml = ET.Element("namelist")
#创建一个根节点 - <namelist></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) #打印生成的格式