python笔记 - day7

参考:

http://www.cnblogs.com/wupeiqi/articles/5501365.html

面向对象,初级篇:
 

大纲:

configparser模块
XML模块
shutil模块以及压缩包处理
subprocess模块
面向对象学习
 

configparser:

模块解析:configparser用于处理特定格式的文件,其本质上是利用open来操作文件。

# 注释1
; 注释2 [section1] # 节点
k1 = v1 # 值
k2:v2 # 值 [section2] # 节点
k1 = v1 # 值 configparser只能编辑这种格式的配置文件,例如samba

配置文件示例

1.获取所有节点

import configparser

config = configparser.ConfigParser()
config.read('xxxooo', encoding='utf-8')
ret = config.sections()
print(ret)

2、获取指定节点下所有的键值对

import configparser

config = configparser.ConfigParser()
config.read('xxxooo', encoding='utf-8')
ret = config.items('section1')
print(ret)

3、获取指定节点下所有的建

import configparser

config = configparser.ConfigParser()
config.read('xxxooo', encoding='utf-8')
ret = config.options('section1')
print(ret)

4、获取指定节点下指定key的值

import configparser

config = configparser.ConfigParser()
config.read('xxxooo', 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('xxxooo', encoding='utf-8') # 检查
has_sec = config.has_section('section1')
print(has_sec) # 添加节点
config.add_section("SEC_1")
config.write(open('xxxooo', 'w')) # 删除节点
config.remove_section("SEC_1")
config.write(open('xxxooo', 'w'))

6、检查、删除、设置指定组内的键值对

import configparser

config = configparser.ConfigParser()
config.read('xxxooo', encoding='utf-8') # 检查
has_opt = config.has_option('section1', 'k1')
print(has_opt) # 删除
config.remove_option('section1', 'k1')
config.write(open('xxxooo', 'w')) # 设置
config.set('section1', 'k10', "123")
config.write(open('xxxooo', 'w'))

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文件

from xml.etree import ElementTree as ET

# 直接解析xml文件
tree = ET.parse('xx.xml') #获取到所有节点
root = tree.getroot()
print(root.tag)
from xml.etree import ElementTree as ET

# 直接解析xml文件
tree = ET.parse('xx.xml') #获取到所有节点
root = tree.getroot() for child in root:
# 遍历XML文档的第二层
print(child.tag,child.attrib)
#获取根节点名,属性名
for grandchild in child:
# 遍历XML文档的第三层
print(grandchild.tag,grandchild.text)
#获取根节点名下的节点名,和内容

修改,删除,保存文件操作:

from xml.etree import ElementTree as ET

# 直接解析xml文件
tree = ET.parse('xx.xml') # 获取xml文件的根节点
root = tree.getroot()
print(root.tag) #获取顶层标签
for node in root.iter('year'):
new_year = int(node.text) + 1
# 将year节点中的内容自增一
node.text = str(new_year) # 设置属性
node.set('name','alex')
node.set('age','')
# 删除属性
# del node.attrib['name'] #保存文件
tree.write("newxx.xml",encoding='utf-8')

创建XML文档

from xml.etree import ElementTree as ET

# 创建根节点
root = ET.Element("famliy") # 创建节点大儿子
son1 = ET.Element('son', {'name': '儿1'})
# 创建小儿子
son2 = ET.Element('son', {"name": '儿2'}) # 在大儿子中创建两个孙子
grandson1 = ET.Element('grandson', {'name': '儿11'})
grandson2 = ET.Element('grandson', {'name': '儿12'})
son1.append(grandson1)
son1.append(grandson2) # 把儿子添加到根节点中
root.append(son1)
root.append(son1) tree = ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False) 创建方式(一)

创建XML方法一:

from xml.etree import ElementTree as ET

# 创建根节点
root = ET.Element("famliy") # 创建大儿子
# son1 = ET.Element('son', {'name': '儿1'})
son1 = root.makeelement('son', {'name': '儿1'})
# 创建小儿子
# son2 = ET.Element('son', {"name": '儿2'})
son2 = root.makeelement('son', {"name": '儿2'}) # 在大儿子中创建两个孙子
# grandson1 = ET.Element('grandson', {'name': '儿11'})
grandson1 = son1.makeelement('grandson', {'name': '儿11'})
# grandson2 = ET.Element('grandson', {'name': '儿12'})
grandson2 = son1.makeelement('grandson', {'name': '儿12'}) son1.append(grandson1)
son1.append(grandson2) # 把儿子添加到根节点中
root.append(son1)
root.append(son1) tree = ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False) 创建方式(二)

创建XML方法二:

from xml.etree import ElementTree as ET

# 创建根节点
root = ET.Element("famliy") # 创建节点大儿子
son1 = ET.SubElement(root, "son", attrib={'name': '儿1'})
# 创建小儿子
son2 = ET.SubElement(root, "son", attrib={"name": "儿2"}) # 在大儿子中创建一个孙子
grandson1 = ET.SubElement(son1, "age", attrib={'name': '儿11'})
grandson1.text = '孙子' et = ET.ElementTree(root) #生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True, short_empty_elements=False) 创建方式(三)

创建XML方法三:

由于原生保存的XML时默认无缩进,如果想要设置缩进的话, 需要修改保存方式:

from xml.etree import ElementTree as ET
from xml.dom import minidom def prettify(elem):
"""将节点转换成字符串,并添加缩进。
"""
rough_string = ET.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t") # 创建根节点
root = ET.Element("famliy") # 创建大儿子
# son1 = ET.Element('son', {'name': '儿1'})
son1 = root.makeelement('son', {'name': '儿1'})
# 创建小儿子
# son2 = ET.Element('son', {"name": '儿2'})
son2 = root.makeelement('son', {"name": '儿2'}) # 在大儿子中创建两个孙子
# grandson1 = ET.Element('grandson', {'name': '儿11'})
grandson1 = son1.makeelement('grandson', {'name': '儿11'})
# grandson2 = ET.Element('grandson', {'name': '儿12'})
grandson2 = son1.makeelement('grandson', {'name': '儿12'}) son1.append(grandson1)
son1.append(grandson2) # 把儿子添加到根节点中
root.append(son1)
root.append(son1) raw_str = prettify(root) f = open("xxxoo.xml",'w',encoding='utf-8')
f.write(raw_str)
f.close()

缩进保存方法:

zipfile,压缩,解压缩文件:

ZIP

import zipfile

#把文件“ooo.xml,newxx.xml”打包成laxi.zip文件
z = zipfile.ZipFile('laxi.zip','w')
z.write('ooo.xml')
z.write('newxx.xml')
z.close() #把t1.py文件,追加打包到laxi.zip文件中
z = zipfile.ZipFile('laxi.zip','a')
z.write('t1.py')
z.close() #解压laxi.zip这个包文件
z = zipfile.ZipFile('laxi.zip','r')
z.extract()
z.close() #单独把“ooo.xml”文件解压出来
z = zipfile.ZipFile('laxi.zip','r')
z.extract('ooo.xml') #打印出来“laxi.zip”压缩包中,打包了哪些文件
z = zipfile.ZipFile('laxi.zip','r')
for item in z.namelist():
print(item,type(item))

tarfile

import tarfile

#把“t1.py重命名成t1bak.py”
#把“t2.py重命名成t2bak.py”
#然后把这两个文件打包成your.tar文件
tar = tarfile.open('your.tar','w')
tar.add('t1.py',arcname='t1bak.py')
tar.add('t2.py',arcname='t2bak.py')
tar.close() #把t1.py文件重命名后追加打包到your.tar文件中
tar = tarfile.open('your.tar','a')
tar.add('t1.py',arcname='t3bak.py')
tar.close() #解压your.tar这个文件
tar = tarfile.open('your.tar','r')
tar.extractall()
tar.close() #只解压t1bak.py这个文件
tar = tarfile.open('your.tar','r')
tar.extract('t1bak.py')
tar.close() #打印出your.tar包中的所有文件
tar = tarfile.open('your.tar','r')
for item in tar.getmembers():
print(item)

subprocess执行系统命令:

shell=False传列表,shell等于True传字符串

call 

执行命令,返回状态码

ret = subprocess.call(["ls", "-l"], shell=False)
ret = subprocess.call("ls -l", shell=True)

check_call

执行命令,如果执行状态码是 0 ,则返回0,否则抛异常

import subprocess
subprocess.check_call(["ls", "-l"])
subprocess.check_call("exit 1", shell=True) ret = subprocess.call(["ipconfig"],shell=False)
print(ret) ret = subprocess.call("ipconfig",shell=True)
print(ret)

check_output

执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常

subprocess.check_output(["echo", "Hello World!"])
subprocess.check_output("exit 1", shell=True)

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()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
import subprocess
ret1 = subprocess.Popen(["mkdir","t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)

终端输入的命令分为两种:

  • 输入即可得到输出,如:ifconfig
  • 输入进行某环境,依赖再输入,如:python
import subprocess

obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)
import subprocess

obj = subprocess.Popen(["python"],
stdin=subprocess.PIPE, #写管道
stdout=subprocess.PIPE, #拿结果管道
stderr=subprocess.PIPE, #拿错误结果管道
universal_newlines=True) #输入两个命令
obj.stdin.write("print(1)\n")
obj.stdin.write("print(2)")
obj.stdin.close() #取输出结果
cmd_out = obj.stdout.read()
obj.stdout.close() #取错误输出结果
cmd_error = obj.stderr.read()
obj.stderr.close() #打印结果
print(cmd_out)
print(cmd_error)

python笔记 - day7的更多相关文章

  1. Python笔记之不可不练

    如果您已经有了一定的Python编程基础,那么本文就是为您的编程能力锦上添花,如果您刚刚开始对Python有一点点兴趣,不怕,Python的重点基础知识已经总结在博文<Python笔记之不可不知 ...

  2. boost.python笔记

    boost.python笔记 标签: boost.python,python, C++ 简介 Boost.python是什么? 它是boost库的一部分,随boost一起安装,用来实现C++和Pyth ...

  3. 20.Python笔记之SqlAlchemy使用

    Date:2016-03-27 Title:20.Python笔记之SqlAlchemy使用 Tags:python Category:Python 作者:刘耀 博客:www.liuyao.me 一. ...

  4. Python笔记——类定义

    Python笔记——类定义 一.类定义: class <类名>: <语句> 类实例化后,可以使用其属性,实际上,创建一个类之后,可以通过类名访问其属性 如果直接使用类名修改其属 ...

  5. 13.python笔记之pyyaml模块

    Date:2016-03-25 Title:13.Python笔记之Pyymal模块使用 Tags:Python Category:Python 博客地址:www.liuyao.me 作者:刘耀 YA ...

  6. 8.python笔记之面向对象基础

    title: 8.Python笔记之面向对象基础 date: 2016-02-21 15:10:35 tags: Python categories: Python --- 面向对象思维导图 (来自1 ...

  7. python笔记 - day8

    python笔记 - day8 参考: http://www.cnblogs.com/wupeiqi/p/4766801.html http://www.cnblogs.com/wupeiqi/art ...

  8. python笔记 - day7-1 之面向对象编程

    python笔记 - day7-1 之面向对象编程 什么时候用面向对象: 多个函数的参数相同: 当某一些函数具有相同参数时,可以使用面向对象的方式,将参数值一次性的封装到对象,以后去对象中取值即可: ...

  9. python笔记 - day6

    python笔记 - day6 参考: http://www.cnblogs.com/wupeiqi/articles/5501365.html 大纲: 利用递归,实现阶乘: Python反射 pyt ...

随机推荐

  1. MySQL添加字段和修改字段的方法

    添加表字段 alter table table1 add transactor varchar(10) not Null; alter table   table1 add id int unsign ...

  2. 转:mysql中int、bigint、smallint 和 tinyint的区别与长度的含义

    bigint 从 -2^63 (-9223372036854775808) 到 2^63-1 (9223372036854775807) 的整型数据(所有数字).存储大小为 8 个字节. P.S. b ...

  3. Java导出Highcharts生成的图表为图片源码

    本文转载自:http://blog.csdn.net/dengsilinming/article/details/7352054 需要的jar包: 需要的js文件:(可以通过http://www.hi ...

  4. select @@identity的用法

    用select @@identity得到上一次插入记录时自动产生的ID 如果你使用存储过程的话,将非常简单,代码如下:SET @NewID=@@IDENTITY 说明: 在 一条 INSERT.SEL ...

  5. GetSystemMetrics()

    GetSystemMetrics()函数的用法 可以用GetSystemMetrics函数可以获取系统分辨率,但这只是其功能之一,GetSystemMetrics函数只有一个参数,称之为「索引」,这个 ...

  6. MHA监控进程异常退出

    这两天遇到一个非常诡异的问题,打算和大家分享一下.只所以诡异估计是自己知识面不够吧.线上的MHA一直没有开启自动切换,都是手动切换的,最近开启了自动切换以后,退出securecrt窗口以后发现监控进程 ...

  7. iOS - AVAudioPlayer 音频播放

    前言 NS_CLASS_AVAILABLE(10_7, 2_2) @interface AVAudioPlayer : NSObject @available(iOS 2.2, *) public c ...

  8. 《Java核心技术卷二》笔记(三)正则表达式

    正则表达式语法 一个正则表达式描述了字符串的构成规则(模式).如果一个具体的字符串正好符合正则表达式描述的这个规则,这个字符串就是与表达式匹配的.先看一下怎么描述这种规则,也就是正则表达式语法.正则表 ...

  9. 利用反射得到android存储路径

    获得android手机的存储路径: public String getPrimaryStoragePath(){ try{ StorageManager sm = (StorageManager) c ...

  10. caca393刷PTP教程

        http://www.chickenclix.com/ 让大家等急了,最近真是很忙,对不住了:)好了闲话少说开始讲正题,再说可能有人要拍砖了............我们就以http://www ...