python study to 7 基础篇
模块
configparser模块
configparser用于处理特定格式的文件, 本质上来讲利用Open操作文件
例如以下格式文件:
1 [section1] 2 k1 = Ture 3 k2 = v2 4 k10 = 123 5 6 [section2] 7 k1 = v1
以下为configparser操作例子:
例1、获取所有节点
import configparser config = configparser.ConfigParser() config.read("file" ,encoding="utf-8") ret = config.sections() print(ret)
例2、获取指定节点下的所有键值对
import configparser config = configparser.ConfigParser() config.read("file",encoding="utf-8") ret = config.items("section1") print(ret)
例3、获取指定节点下的所有键
import configparser config = configparser.ConfigParser() config.read("file",encoding="utf-8") ret = config.options("section1") print(ret)
例4、获取指定节点下指定的key值
import configparser config = configparser.ConfigParser() config.read('file', encoding='utf-8') # v = config.get('section1', 'k1') # v = config.getint('section1', 'k1') # v = config.getfloat('section1', 'k1') v = config.getboolean('section1', 'k1') print(v)
例5、检查、删除、添加节点
import configparser config = configparser.ConfigParser() config.read('file', encoding='utf-8') 检查节点 has_sec =config.has_section("section1")#检查节点是否存在,存在返回True,不存在返回True print(has_sec) 添加节点 config.add_section("SEC_1") config.write(open("file","w")) 删除节点 config.remove_section("SEC_1") config.write(open("file","w"))
例6、检查、删除、设置指定组内的键值对
import configparser config = configparser.ConfigParser() config.read('file', encoding='utf-8') 检查 has_opt = config.has_option("section1","k1") print(has_opt) 删除 config.remove_option("section1","k1") config.write(open("file","w")) 设置 config.set("section1","k10","123") config.write(open("file","w"))
XML
XML实现不同语言和程序之间进行数据交换的协议
<data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2023</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2026</year> <gdppc>59900</gdppc> <neighbor direction="N" name="Malaysia" /> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2026</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country> </data>
xml的功能和用途:
xml 在页面上做展示(字符串类型的一个xml格式数据)、做配置文件(文件,内部数据xml格式)每一个节点都是一个Element,每一个节点就是Element 对象。
解析xml文件两种不同的方式
1、 from xml.etree import ElementTree as ET # 打开文件,读取XML内容 str_xml = open('xo.xml', 'r').read() # 将字符串解析成xml特殊对象,root代指xml文件的根节点 root = ET.XML(str_xml) 2、 from xml.etree import ElementTree as ET # 直接解析xml文件 tree = ET.parse("xo.xml") # 获取xml文件的根节点 root = tree.getroot()#
遍历整个xml文件,然后可选择打印 节点名、节点所带的属性、节点之间的内容
1 from xml.etree import ElementTree as ET 2 tree = ET.parse("newnew.xml") 3 root = tree.getroot() 4 for child in root: 5 print(child.tag,child.attrib) 6 for gradechild in child: 7 print(gradechild.tag,gradechild.attrib ,gradechild.text)
修改节点内容方式:
1、解析方式字符串,修改,保存
1 from xml.etree import ElementTree as ET 2 3 ############ 解析方式一 ############ 4 5 # 打开文件,读取XML内容 6 str_xml = open('newnew.xml', 'r').read() 7 8 # 将字符串解析成xml特殊对象,root代指xml文件的根节点 9 root = ET.XML(str_xml) 10 11 ############ 操作 ############ 12 13 # 顶层标签 14 print(root.tag) 15 16 # 循环所有的year节点 17 for node in root.iter('year'): 18 # 将year节点中的内容自增一 19 new_year = int(node.text) + 1 20 node.text = str(new_year) 21 22 # 设置属性 23 node.set('name', 'alex') 24 node.set('age', '18') 25 # 删除属性 26 del node.attrib['name'] 27 28 ############ 保存文件 ############ 29 tree = ET.ElementTree(root) #以字符串打开xml文件方式,不能直接把内存中的数据写入文件,需要调用ElementTree 30 tree.write("new.xml", encoding='utf-8') #调用ElementTree直接把数据写入文件。
2、解析文件方式,修改,保存
1 from xml.etree import ElementTree as ET 2 3 ############ 解析方式二 ############ 4 5 # 直接解析xml文件 6 tree = ET.parse("new.xml") 7 8 # 获取xml文件的根节点 9 root = tree.getroot() 10 11 ############ 操作 ############ 12 13 # 顶层标签 14 print(root.tag) 15 16 循环所有的year节点 17 for node in root.iter('year'): 18 # 将year节点中的内容自增一 19 new_year = int(node.text) + 1 20 node.text = str(new_year) 21 22 # 设置属性 23 node.set('name', 'alex') 24 node.set('age', '18') 25 # 删除属性 26 del node.attrib['name'] 27 28 ############ 保存文件 ############ 29 tree.write("newnew.xml", encoding='utf-8')
删除节点:
1 from xml.etree import ElementTree as ET 2 3 ############ 解析字符串方式打开 ############ 4 5 # 打开文件,读取XML内容 6 str_xml = open('xo.xml', 'r').read() 7 8 # 将字符串解析成xml特殊对象,root代指xml文件的根节点 9 root = ET.XML(str_xml) 10 11 ############ 操作 ############ 12 13 # 顶层标签 14 print(root.tag) 15 16 # 遍历data下的所有country节点 17 for country in root.findall('country'): 18 # 获取每一个country节点下rank节点的内容 19 rank = int(country.find('rank').text) 20 21 if rank > 50: 22 # 删除指定country节点 23 root.remove(country) 24 25 ############ 保存文件 ############ 26 tree = ET.ElementTree(root) 27 tree.write("newnew.xml", encoding='utf-8')
1 from xml.etree import ElementTree as ET 2 3 ############ 解析文件方式 ############ 4 5 # 直接解析xml文件 6 tree = ET.parse("xo.xml") 7 8 # 获取xml文件的根节点 9 root = tree.getroot() 10 11 ############ 操作 ############ 12 13 # 顶层标签 14 print(root.tag) 15 16 # 遍历data下的所有country节点 17 for country in root.findall('country'): 18 # 获取每一个country节点下rank节点的内容 19 rank = int(country.find('rank').text) 20 21 if rank > 50: 22 # 删除指定country节点 23 root.remove(country) 24 25 ############ 保存文件 ############ 26 tree.write("newnew.xml", encoding='utf-8')
xml文件创建节点:
1 from xml.etree import ElementTree as ET 2 3 # 创建根节点 4 root = ET.Element("famliy") 5 6 from xml.etree import ElementTree as ET 7 8 # 创建根节点 9 root = ET.Element("famliy") 10 # # 11 # 创建节点大儿子 12 son1 =ET.Element("son",{"name":"儿1"}) 13 # 创建小儿子 14 son2 =ET.Element("son",{"name":"儿2"}) 15 16 # 在大儿子中创建两个孙子 17 grandson1 = ET.Element("grandson",{"name":"儿11"}) 18 grandson2 = ET.Element("grandson",{"name":"儿11"}) 19 son1.append(grandson1) 20 son1.append(grandson2) 21 22 # 把儿子添加到根节点中 23 root.append(son1) 24 root.append(son1) 25 26 tree = ET.ElementTree(root) 27 tree.write("xml",encoding="utf-8",xml_declaration=True,short_empty_elements=False) #xml_declaration=True 缩进
1 from xml.etree import ElementTree as ET 2 3 # 创建根节点 4 root = ET.Element("famliy") 5 6 7 # 创建大儿子 8 # son1 = ET.Element('son', {'name': '儿1'}) 9 son1 = root.makeelement('son', {'name': '儿1'}) 10 # 创建小儿子 11 # son2 = ET.Element('son', {"name": '儿2'}) 12 son2 = root.makeelement('son', {"name": '儿2'}) 13 14 # 在大儿子中创建两个孙子 15 # grandson1 = ET.Element('grandson', {'name': '儿11'}) 16 grandson1 = son1.makeelement('grandson', {'name': '儿11'}) 17 # grandson2 = ET.Element('grandson', {'name': '儿12'}) 18 grandson2 = son1.makeelement('grandson', {'name': '儿12'}) 19 20 son1.append(grandson1) 21 son1.append(grandson2) 22 23 24 # 把儿子添加到根节点中 25 root.append(son1) 26 root.append(son1) 27 28 tree = ET.ElementTree(root) 29 tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)
1 from xml.etree import ElementTree as ET 2 3 4 # 创建根节点 5 root = ET.Element("famliy") 6 7 8 # 创建节点大儿子 9 son1 = ET.SubElement(root, "son", attrib={'name': '儿1'}) 10 # 创建小儿子 11 son2 = ET.SubElement(root, "son", attrib={"name": "儿2"}) 12 13 # 在大儿子中创建一个孙子 14 grandson1 = ET.SubElement(son1, "age", attrib={'name': '儿11'}) 15 grandson1.text = '孙子' 16 17 18 et = ET.ElementTree(root) #生成文档对象 19 et.write("test.xml", encoding="utf-8", xml_declaration=True, short_empty_elements=False)
保存原生xml文件时无缩进,如果需要保存需要保存缩进方式
1 from xml.etree import ElementTree as ET 2 from xml.dom import minidom 3 4 5 def prettify(elem): 6 """将节点转换成字符串,并添加缩进。 7 """ 8 rough_string = ET.tostring(elem, 'utf-8') 9 reparsed = minidom.parseString(rough_string) 10 return reparsed.toprettyxml(indent="\t") 11 12 # 创建根节点 13 root = ET.Element("famliy") 14 15 16 # 创建大儿子 17 # son1 = ET.Element('son', {'name': '儿1'}) 18 son1 = root.makeelement('son', {'name': '儿1'}) 19 # 创建小儿子 20 # son2 = ET.Element('son', {"name": '儿2'}) 21 son2 = root.makeelement('son', {"name": '儿2'}) 22 23 # 在大儿子中创建两个孙子 24 # grandson1 = ET.Element('grandson', {'name': '儿11'}) 25 grandson1 = son1.makeelement('grandson', {'name': '儿11'}) 26 # grandson2 = ET.Element('grandson', {'name': '儿12'}) 27 grandson2 = son1.makeelement('grandson', {'name': '儿12'}) 28 29 son1.append(grandson1) 30 son1.append(grandson2) 31 32 33 # 把儿子添加到根节点中 34 root.append(son1) 35 root.append(son1) 36 37 38 raw_str = prettify(root) 39 40 f = open("xxxoo.xml",'w',encoding='utf-8') 41 f.write(raw_str) 42 f.close()
subprocess模块(系统命令)
python3.0之前可执行shell命令相关模块和函数有:os.popen、os.system、os.spawn、popen2.、commands
python3.0中整合了以针对于执行shell 命令的模块和函数,python3.0中的模块为subprocess,同时subprocess提供了非常丰富的操作系统shell命令模块和函数
call执行命令返回状态码
import subprocess ret = subprocess.call(["netstat","-e"],shell=False) #shell等于Flase的时候,传列表 ret = subprocess.call(["netstat"],shell=True) #shell等于True的时候,传字符串
check_call执行命令,如果执行状态码是0,则返回0,否则抛出异常
import subprocess subprocess.check_call(["netstat","-t"]) subprocess.check_call("dir",shell=True)
check_output执行命令,如果状态码是0,则返回执行结果,否则抛出异常
import subprocess subprocess.check_output(["echo","hello world"]) ret=subprocess.check_output("netstat",shell="True") print(ret)
subprocess.popen()
用于执行复杂的系统命令
subprocess.popen 的参数:
args:shell命令,可以是字符串或者序列类型(如:list,元组) bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲 stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄 preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用 close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。 所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。 shell:同上 cwd:用于设置子进程的当前目录 env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。 universal_newlines:不同系统的换行符不同,True -> 同意使用 \n startupinfo与createionflags只在windows下有效 将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
终端输入命令分为两种:
输入即可得到输出,如:ifconfig
输入进行某些环境依赖再输入,如python
例1:指定一个目录
1 import subprocess 2 obj = subprocess.Popen("mkdir t3",shell=True,cwd="/home/dev",)
例2:管道方式输入
1 import subprocess 2 obj = subprocess.Popen(["python"],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True) 3 obj.stdin.write("print(1)\n") 4 obj.stdin.write("print(2)") 5 obj.stdin.close()
例3:管道方式代码简写:1
1 import subprocess 2 obj = subprocess.Popen(["python"],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True) 3 obj.stdin.write("print(1)\n") 4 obj.stdin.write("print(2)") 5 6 out_error_list = obj.communicate() #自动帮助执行stdout 和 stdout 7 print(out_error_list)
例4:管道方式代码简写:2
1 import subprocess 2 obj = subprocess.Popen(["python"],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True) 3 out_error_list = obj.communicate('print("hello")') 4 print(out_error_list)
面向对象编程
面向对象语法格式:
a.创建类 class 类名: def 方法名(self,para): pass b. 创建对象 对象 = 类名()#变量等于类名后面加一个括号,即创建一个对象。 c.通过对象执行方法 对象.方法名(123) 例如: class student: def sport(self,para): pass jack = student() jack.sport(123)
面向对象的三个特性:封装、继承、多态
封装:
例1
class sqlhelper: def fetch(self,sql): pass def create(self,sql): pass def remove(self,nid): pass def modify(self,name): pass obj = sqlhelper() obj.hhost = "c1.salt.com" obj.uusername = "alex" obj.pwd = "123" obj.fetch("select * from A")
面向对象的构造方法:
__init__
class SQLHlper: def __init__(self,a1,a2,a3): print("自动执行init") self.hhost = a1 self.uusername = a2 self.pwd = a3 def fetch(self,sql): pass def create(self,sql): pass def remove(self,nid): pass def modify(self,name): pass obj1 = SQLHlper("c1.salt.com","alex",123) obj1.fetch("select * from A")