configparser模块

configparser用于拍卖特定格式的文件,其本质是接纳open来操作文件。

文件a.txt

  1. [section1]

  2. k1 = 123

  3. k2:v2

  4.  

  5. [section2]

  6. k1 = 234

加载文件a.txt

  1. import configparser

  2.  

  3. config = configparser.ConfigParser()

  1. config.read(‘a.txt’,encoding=’utf-8′)

对文本有关操作

  1. import configparser

  2.  

  3. config = configparser.ConfigParser()

  1. config.read(‘a.txt’,encoding=’utf-8′)
  1.  

  2. #得到具有节点

  3. ret = config.sections()

  4. print(ret)

  5.  

  6. #获取指定节点下的富有键值对

  7. ret = config.items(‘section1’)

  8. print(ret)

  9.  

  10. #得到指定节点下拥有的键

  11. ret = config.options(‘section1’)

  1. print(ret)

  2.  

  3. #获取指定节点下指定key的值

  4.  

  5. ret = config.get(‘section1′,’k1’)

  6. #转换成int

  7. # ret = config.getint(‘section1′,’k1’)

  1. #转换成float

  2. # ret =
    config.getfloat(‘section1′,’k1’)

  3. #转换成boolean

  4. # ret =
    config.getboolean(‘section1′,’k1’)

  5.  

  6. print(ret)

  7.  

  8. #自我批评、删除、设置指定组内的键值对

  1.  

  2. #检查

  3. has_opt =
    config.has_option(‘section1’)

  4. print(has_opt)

  5.  

  6. #添加节点

  7. config.add_section(‘SEC_1’)

  8. config.write(open(‘a.txt’,’w’))

  9.  

  10. #除去节点

  11. config.remove_section(‘SEC_1’)

  1. config.write(open(‘a.txt’,’w’))

  2.  

  3. #自我批评、删除、设置指定组内的键值对

  1.  

  2. #检查

  3. has_opt =
    config.has_option(‘section1′,’k1’)

  4. print(has_opt)

  5.  

  6. #删除

  7. config.remove_option(‘section1′,’k1’)

  1. config.write(open(‘a.txt’,’w’))

  2.  

  3. #设置

  4. config.set(‘section1′,’k10′,’123’)

  5. config.write(open(‘a.txt’,’w’))

XML模块

xml是落实不同语言或程序之间举行数据互换的说道。

文件xml_text.xml

  1. <data>

  2.     <country name=”Liechtenstenin”>

  3.         <rank update=”yes”>2</rank>

  4.         <year>2023</year>

  1.         <gdppc>141100</gbppc>
  1.         <neighbor direction=”E” name=”Austria”/>

  2.         <neighbor direction=”W” name=”Switzerland”/>

  3.     </country>

  4.     <country name=”Sinagapore”>

  5.         <rank update=”yes”>5</rank>

  6.         <year>2026</year>

  1.         <gdppc>59900</gdppc>
  1.         <neighbor direction=”N” name=”Malaysia”/>

  2.     </country>

  3.     <country name=”Panama”>

  4.         <rank update=”yes”>69</rank>

  5.         <year>2026</year>

  1.         <gdppc>13600</gdppc>
  1.         <neighbor direction=”W” name=”Costa Rica”/>

  2.         <neighbor direction=”E” name=”Costa Rica”/>

  3.     </country>

  4. </data>

xml相关操作

解析xml文件

  1. from xml.etree import ElementTree as ET

  2. #从来解析xml文件

  3. tree = ET.parse(‘xml_test.xml’)

  1.  

  2. #取得xml文件的根节点

  3. root = tree.getroot()

  4. print(root)

  5. print(root.tag)

  6. print(root.attrib)

  7. “””

  8. 输出:

  9. <Element ‘data’ at
    0x00000000006D0688>

  10. data

  11. {‘title_2’: ‘test_2’, ‘title_1’:
    ‘test_1’}

  12. “””

分析字符串

  1. from xml.etree import ElementTree as ET

  2.  

  3. #开辟文件,读取xml内容

  4. str_xml =
    open(‘xm_test.xml’,’r’).read()

  5.  

  6. #将字符串解析成xml特殊目的,root代指xml文件的根节点

  1. root = ET.XML(str_xml)

遍历xml文档的具有情节

  1. from xml.etree import ElementTree as ET

  2. #直白解析xml文件

  3. tree = ET.parse(‘xml_test.xml’)

  1.  

  2. #得到xml文件的根节点

  3. root = tree.getroot()

  4. #遍历xml文档的第二层

  5. for
    child in root:

  6.     #其次层节点的标签名称和标签属性

  1.     print(child.tag,child.attrib)
  1.     #遍历xml文档的第三层

  2.     for i in
    child:

  3.         #其三层节点的竹签名称和内容

  1.         print(i.tag,i.text)

  2. “””

  3. 输出:

  4. country {‘name’: ‘Liechtenstenin’}

  1. rank 2

  2. year 2023

  3. gdppc 141100

  4. neighbor None

  5. neighbor None

  6. country {‘name’: ‘Sinagapore’}

  7. rank 5

  8. year 2026

  9. gdppc 59900

  10. neighbor None

  11. country {‘name’: ‘Panama’}

  12. rank 69

  13. year 2026

  14. gdppc 13600

  15. neighbor None

  16. neighbor None

  17. “””

修改xml

分析字符串模式展开改动

  1. from xml.etree import ElementTree as ET

  2. str_xml =
    open(‘xml_test.xml’,’r’).read()

  3. root = ET.XML(str_xml)

  4.  

  5. #获取顶层标签

  6. print(root.tag)

  7.  

  8. #循环所有的year节点

  9. for
    node in root.iter(‘year’):

  10.     #将year节点中的内容自增一

  11.     new_year = int(node.text) + 1

  12.     node.text = str(new_year)

  13.  

  14.     #设置属性

  15.     node.set(‘name’,’alex’)

  16.     node.set(‘age’,’19’)

  17.  

  18.     #去除属性

  19.     del node.attrib[‘name’]

  20.  

  21. #履新文件

  22. tree = ET.ElementTree(root)

  23. tree.write(“new_xml_test.xml”,encoding=’utf-8′)

浅析文件格局展开改动

一向调用tree.write写入即可。

  1. from xml.etree import ElementTree as ET

  2. tree = ET.parse(‘xml_test.xml’)

  1. root = tree.getroot()

  2.  

  3. “””

  4. 操作

  5. “””

  6.  

  7. #更新文件

  8. tree.write(“new_xml_test2.xml”,encoding=’utf-8′)

添加节点

  1. from xml.etree import ElementTree as ET

  2. tree = ET.parse(‘xml_test.xml’)

  1. root = tree.getroot()

  2.  

  3. ele = ET.Element(‘Alex’,{‘k1′:’v1’})

  1. ele.text = “test”

  2. root.append(ele)

  3.  

  4. tree.write(“new.xml”,encoding=’utf-8′)

结果new.xml:

  1. <data title_1=”test_1″ title_2=”test_2″>

  2.  

  3. “””

  4. 原内容

  5. “””

  6.  

  7. <Alex k1=”v1″>test</Alex></data>

是因为原生保存xml时默认无缩进,要是要安装缩进需要修改保存方法。

  1. from xml.etree import ElementTree as ET

  2. from xml.dom import minidom

  3.  

  4. def prettify(elem):

  5.     “””

  6.     将节点转换成字符串,并添加缩进

  1.     :param elem:

  2.     :return:

  3.     “””

  4.     rough_string =
    ET.tostring(elem,’utf-8′)

  5.     reparsed =
    minidom.parseString(rough_string)

  6.     return reparsed.toprettyxml(indent=”\t”)

  7.  

  8. #创办根节点

  9. root = ET.Element(“family”)

  10.  

  11. #制造三外甥

  12. # son1 =
    ET.Element(‘son’,{‘name’:’儿1′})

  13. son1 =
    root.makeelement(‘son’,{‘name’:’儿1′})

  14. #始建三外甥

  15. # son2 =
    ET.Element(‘son’,{‘name’:’儿2′})

  16. son2 =
    root.makeelement(‘son’,{‘name’:’儿2′})

  17.  

  18. #在外甥中成立2个外孙子

  19. # grandson1 =
    ET.Element(‘grandson’,{‘name’:’儿11′})

  20. grandson1 =
    root.makeelement(‘grandson’,{‘name’:’儿11′})

  21. # grandson2 =
    ET.Element(‘grandon’,{‘name’:’儿12′})

  22. grandson2 =
    root.makeelement(‘grandon’,{‘name’:’儿12′})

  23.  

  24. son1.append(grandson1)

  25. son2.append(grandson2)

  26.  

  27. #把幼子添加到根节点

  28. root.append(son1)

  29. root.append(son2)

  30.  

  31. raw_str = prettify(root)

  32.  

  33. f =
    open(‘family.xml’,’w’,encoding=’utf-8′)

  34. f.write(raw_str)

  35. f.close()

family.xml:

  1. <?xml version=”1.0″ ?>

  2. <family>

  3.    <son name=”儿1″>

  4.       <grandson name=”儿11″/>

  5.    </son>

  6.    <son name=”儿2″>

  7.       <grandon name=”儿12″/>

  8.    </son>

  9. </family>

shutil

尖端的公文、文件夹、压缩包处理模块。

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

将文件内容拷贝到另一个文件中

  1. import shutil

  2.  

  3. shutil.copyfileobj(open(‘old.xml’,’r’),open(‘new.xml’,’w’))

shuit.copyfile(src,dst)

拷贝文件

  1. shutil.copyfile(‘f1.log’,’f2.log’)

zipfile、tarfile

zipfile创制压缩包

  1. import zipfile

  2.  

  3. #压缩

  4. z = zipfile.ZipFile(‘test.zip’,’a’)

  1. z.write(‘new.xml’)

  2. z.write(‘family.xml’)

  3. z.close

zipfile解压压缩包

  1. #解压

  2. z = zipfile.ZipFile(‘test.zip’,’r’)

  1.  

  2. #解压整体

  3. # z.extractall()

  4.  

  5. #解压单个文件

  6. z.extract(“new.xml”)

  7.  

  8. #取得压缩包的分子

  9. for
    item in z.namelist():

  10.     print(item)

  11.  

  12. z.close()

tarfile创设压缩包

  1. import tarfile

  2.  

  3. #压缩

  4. tar = tarfile.open(“test.tar”,’w’)

  5. #arcname重命名

  6. tar.add(‘test.py’,arcname=’test_1.py’)

  1. tar.add(‘xml_test.py’,arcname=’xml_test.py’)
  1. tar.close()

tarfile解压压缩包

  1. tar = tarfile.open(‘test.tar’,’r’)
  1.  

  2. #可安装解压路径

  3. # tar.extractall()

  4.  

  5. for
    item in tar.getmembers():

  6.     print(item,type(item))

  7.  

  8. obj = tar.getmember(“test_1.py”)

  9. print(obj,type(obj))

  10. tar.extract(obj)

  11.  

  12. tar.close()

系统命令

call

赢得状态码,0正常。

  1. import subprocess

  2.  

  3. #shell=False命令传入形式为列表

  4. ret = subprocess.call([“ls”,”-l”],shell=False)

  5.  

  6. #shell=True命令传入模式为字符串

  1. ret = subprocess.call(“ls -l”,shell=True)

check_call

执行命令,倘使实施情状码是0,则再次回到0,否则抛出万分。

  1. ret = subprocess.check_call(“ls -l”,shell=True)

check_output

执行命令,如若处境码是0,则赶回执行结果,否则抛出分外。

  1. ret = subprocess.check_output(“ls -l”,shell=True)

函数式编程和面向对象编程实现殡葬邮件功用。

函数实现:

  1. def mail(email,message):

  2.     print(“发送”)

  3.    return True

  4.  

  5. mail(“xxxx.@126.com”,”hello”)

面向对象实现:

  1. class
    Foo:

  2.     #方法

  3.    def mail(self,email,message):

  1.        print(“发送”)

  2.       return True

  3.  

  4. #调用

  5. #1、创造对象,类名()

  6. obj = Foo()

  7. #2、通过对象去实施办法

  8. obj.mail(“xxxx.@126.com”,”hello”)

类和对象

1、创建类:

class 类名:

def 方法名(self,xxx):

pass

2、成立对象

对象 = 类名()

3、通过对象进行办法

对象.方法名(xxx)

函数式

def fetch(host,username,passwd,sql):

pass

def create(host,username,passwd,sql):

pass

def remove(host,username,passwd,sql):

pass

def modify(host,username,passwd,sql):

pass

fetch(…)

面向对象:

class SQLHelper:

def fetch(self,host,username,passwd,sql):

pass

def create(self,host,username,passwd,sql):

pass

def remove(self,host,username,passwd,nid):

pass

def modify(self,host,username,passwd,name):

pass

obj = SQLHelper()

obj.fetch(…)

面向对象优化:

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 = “xxx.xxx.xxx”

obj.uusername = “xxxx”

obj.passwd = “xxxx”

obj.fetch(“sql”)

  1. class
    SQLHelper:

  2.     def fetch(self, sql):

  3.         #链接数据库

  4.         print(self.hhost)

  5.         print(self.uusername)

  6.         print(self.passwd)

  7.         print(sql)

  8.     def create(self,sql):

  9.         pass

  10.     def remove(self,nid):

  11.         pass

  12.     def modify(self,name):

  13.         pass

  14. obj = SQLHelper()

  15. obj.hhost = “xxx.xxx.xxx”

  16. obj.uusername = “xxxx”

  17. obj.passwd = “xxxx”

  18. obj.fetch(“select * from A”)

  19. 输出:

  20. xxx.xxx.xxx

  21. xxxx

  22. xxxx

  23. select * from A

怎样时候使用面向对象?

当一些函数具有同样参数时,可以采用面向对象的形式,将参数值一次性打包到目的中,方便未来去对象中取值。

self是什么?

self是一个python自动传值的参数,这多少个目的执行措施,self就是什么人。

obj1 = SQLHelper()

obj1.hhost = “1xxx.xxx.xxx”

obj1.uusername = “xxxx”

obj1.passwd = “xxxx”

obj1.fetch(“sql”) #self==obj1

 

obj2 = SQLHelper()

obj2.hhost = “2xxx.xxx.xxx”

obj2.uusername = “xxxx”

obj2.passwd = “xxxx”

obj2.fetch(“sql”) #self==obj2

构造方法

类中有一个破例的方法__init__,类()自动被实践。

  1. class
    SQLHelper:

  2.     def __init__(self,a1,a2,a3):

  1.         self.hhost = a1

  2.         self.uusername = a2

  3.         self.passwd = a3

  4.         print(“自动执行init”)

  5.     def fetch(self, sql):

  6.         #链接数据库

  7.         print(self.hhost)

  8.         print(self.uusername)

  9.         print(self.passwd)

  10.         print(sql)

  11.     def create(self,sql):

  12.         pass

  13.     def remove(self,nid):

  14.         pass

  15.     def modify(self,name):

  16.         pass

  17. obj1 = SQLHelper(“1xxx.xxx.xxx”,”xxxx”,”xxxx”)

  18. obj1.fetch(“select * from A”)

  19. obj2 = SQLHelper(“2xxx.xxx.xxx”,”xxxx”,”xxxx”)

  20. obj2.fetch(“select * form A”)

  21. 输出:

  22. 机关执行init

  23. 1xxx.xxx.xxx

  24. xxxx

  25. xxxx

  26. select * from A

  27. 自行执行init

  28. 2xxx.xxx.xxx

  29. xxxx

  30. xxxx

  31. select * form A

面向对象三大特点:封装、继承、多态。

封装

面向对象的程序设计中,某个类把所需要的数额(类的习性)和对数据的操作(类的行为)全部都封装在类中,分别称为类的积极分子变量和章程(成员函数)。这种把成员变量和成员函数封装在联合的编程特性称为封装。

  1. class
    c1:

  2.     def __init__(self,name,obj):

  1.         self.name = name

  2.         self.obj = obj

  3.  

  4. class
    c2:

  5.     def __init__(self,name,age):

  1.         self.name = name

  2.         self.age = age

  3.  

  4.     def show(self):

  5.         print(self.name)

  6.  

  7. class
    c3:

  8.     def __init__(self,a1):

  9.         self.money = 123

  10.         self.aaa = a1

  11.  

  12.  

  13. c2_obj = c2(‘aa’,11)

  14.  

  15. c1_obj = c1(“alex”,c2_obj)

  16. print(c1_obj.obj.age)

  17.  

  18. c3_obj = c3(c1_obj)

  19. print(c3_obj.aaa.obj.age)

  20. 输出:

  21. 11

  22. 11

继承

继续是六个类或五个类之间的父子关系,子进程继续父进程的所有国有实例变量和措施。继承实现了代码的录取。重用已经存在的数目和行事,缩短代码的再度编写,python在类名后用一对圆括号表示继续关系,括号中的类表示父类,虽然父类定义了__init__办法,则子类必须出示地调用父类的__init__艺术,如果子类需要增添父类的一言一行,可以增长__init__主意的参数。

单继承

  1. class
    F1:#父类、基类

  2.     def show(self):

  3.         print(‘show’)

  4.  

  5. #F2继承F1

  6. class
    F2(F1):#子类、派生类

  7.     def bar(self):

  8.         print(‘bar’)

  9.  

  10. obj = F2()

  11. obj.bar()

  12. obj.show()

  13. 输出:

  14. bar

  15. show

 

  1. class
    F1:#父类、基类

  2.     def show(self):

  3.         print(‘show’)

  4.  

  5.     def foo(self):

  6.         print(self.name)

  7.  

  8. #F2继承F1

  9. class
    F2(F1):#子类、派生类

  10.     def __init__(self,name):

  1.         self.name = name

  2.  

  3.     def bar(self):

  4.         print(‘bar’)

  5.  

  6.     def show(self):#协调的先期级更高

  1.         print(‘F2 show’)

  2.  

  3. obj = F2(‘alex’)

  4. obj.bar()

  5. obj.show()

  6. obj.foo()

  7. 输出:

  8. bar

  9. F2 show

  10. alex

 

  1. class
    S1:

  2.     def F1(self):

  3.         self.F2()

  4.  

  5.     def F2(self):

  6.         print(‘S1.F2()’)

  7.  

  8. class
    S2(S1):

  9.     def F3(self):

  10.         self.F1()

  11.  

  12.     def F2(self):

  13.         print(‘S2.F2()’)

  14.  

  15. obj = S2()

  16. obj.F3()

  17. 输出:

  18. S2.F2()

多继承

  1. class
    C1:

  2.     def f1(self):

  3.         pass

  4.  

  5. class
    C2:

  6.     def f2(self):

  7.         pass

  8.  

  9. class
    C3(C2,C1):

  10.     pass

  11.  

  12. obj = C3()

 

  1. class
    C1:

  2.     def f1(self):

  3.         print(“C1.f1()”)

  4.  

  5. class
    C2:

  6.     def f1(self):

  7.         print(“C2.f1()”)

  8.  

  9. class
    C3(C2,C1):

  10.     pass

  11.  

  12. obj = C3()

  13. obj.f1()

  14. 输出:

  15. C2.f1()

 

  1. class
    C0:

  2.     def f1(self):

  3.         print(“C0.f1()”)

  4.  

  5. class
    C1():

  6.     def f1(self):

  7.         print(“C1.f1()”)

  8.  

  9. class
    C2(C0):

  10.     def f2(self):

  11.         print(“C2.f1()”)

  12.  

  13. class
    C3(C2,C1):

  14.     pass

  15.  

  16. obj = C3()

  17. obj.f1()

  18. 输出:

  19. C0.f1()

 

  1. class
    C_2:

  2.     def f1(self):

  3.         print(“C_2.f1()”)

  4.  

  5. class
    C_1(C_2):

  6.     def f1(self):

  7.         print(“C_1.f1()”)

  8.  

  9. class
    C0(C_2):

  10.     def f2(self):

  11.         print(“C0.f1()”)

  12.  

  13. class
    C1(C_1):

  14.     def f1(self):

  15.         print(“C1.f1()”)

  16.  

  17. class
    C2(C0):

  18.     def f2(self):

  19.         print(“C2.f1()”)

  20.  

  21. class
    C3(C2,C1):

  22.     pass

  23.  

  24. obj = C3()

  25. obj.f1()

  26. 输出:

  27. C1.f1()

继续总括

对此继续其情势(属性)可能定义在眼前类,也恐怕源于于基类,所以在形式调用时就需要对如今类和基类进行搜索以确定方法所在的地方。而追寻的各类就是所谓的不二法门分析顺序(MRO、Method
Resolution
Order)。对于单继承来说,MRO一般相比较简单,而对此多延续来说,MRO相比复杂。下边就三种为主的继承情势解析。

图片 1

图片 2

相关文章

网站地图xml地图