python笔记 - day7
python笔记 - day7
参考:
http://www.cnblogs.com/wupeiqi/articles/5501365.html
大纲:
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的更多相关文章
- Python笔记之不可不练
如果您已经有了一定的Python编程基础,那么本文就是为您的编程能力锦上添花,如果您刚刚开始对Python有一点点兴趣,不怕,Python的重点基础知识已经总结在博文<Python笔记之不可不知 ...
- boost.python笔记
boost.python笔记 标签: boost.python,python, C++ 简介 Boost.python是什么? 它是boost库的一部分,随boost一起安装,用来实现C++和Pyth ...
- 20.Python笔记之SqlAlchemy使用
Date:2016-03-27 Title:20.Python笔记之SqlAlchemy使用 Tags:python Category:Python 作者:刘耀 博客:www.liuyao.me 一. ...
- Python笔记——类定义
Python笔记——类定义 一.类定义: class <类名>: <语句> 类实例化后,可以使用其属性,实际上,创建一个类之后,可以通过类名访问其属性 如果直接使用类名修改其属 ...
- 13.python笔记之pyyaml模块
Date:2016-03-25 Title:13.Python笔记之Pyymal模块使用 Tags:Python Category:Python 博客地址:www.liuyao.me 作者:刘耀 YA ...
- 8.python笔记之面向对象基础
title: 8.Python笔记之面向对象基础 date: 2016-02-21 15:10:35 tags: Python categories: Python --- 面向对象思维导图 (来自1 ...
- python笔记 - day8
python笔记 - day8 参考: http://www.cnblogs.com/wupeiqi/p/4766801.html http://www.cnblogs.com/wupeiqi/art ...
- python笔记 - day7-1 之面向对象编程
python笔记 - day7-1 之面向对象编程 什么时候用面向对象: 多个函数的参数相同: 当某一些函数具有相同参数时,可以使用面向对象的方式,将参数值一次性的封装到对象,以后去对象中取值即可: ...
- python笔记 - day6
python笔记 - day6 参考: http://www.cnblogs.com/wupeiqi/articles/5501365.html 大纲: 利用递归,实现阶乘: Python反射 pyt ...
随机推荐
- C++ unordered_map remove 实现哈希表移除
使用C++的unordered_map类型时,我们经常要根据关键字查找,并移除一组映射,在Java中直接用remove即可,而STL中居然没有实现remove这个函数,还要自己写循环来查找要删除项,然 ...
- QInputDialog 使用方法
在Qt中,如果想快速生成一个对话框,可以和用户进行简单的交互,而不需要写一个新的类的时候,就要用到QInputDialog类,这个类就是专门用来建立简单对话框的,其主要能建下列几种对话框:
- uva146 ID码
/*极水的题...*/ #include"iostream"#include"stdio.h"#include"stdlib.h"#incl ...
- javascript判断非空
/* *判断非空 * */ function isEmpty(val){ if(val == null)return true; if(val == undefined || val == 'unde ...
- MS14-025引起的问题 - 1
windows2008有一个叫组策略首选项(Group Policy Preference)的新特性.这个特性可以方便管理员在整个域内部署策略.本文会详细介绍这个组策略首选项的一些缺陷.尤其是当下发的 ...
- 校内OJ 1128 词链(link)(Trie+DFS)
1128: 词链(link) 时间限制: 1 Sec 内存限制: 64 MB 提交: 23 解决: 7 [提交][状态][讨论版] 题目描述 给定一个仅包含小写字母的英文单词表,其中每个单词最多包 ...
- poj2387 初涉最短路
前两天自学了一点点最短路..看起来很简单的样子... 就去kuangbin的专题找了最简单的一道题练手..然后被自己萌萌的三重for循环超时虐的不要不要的~ 松弛虽然会但是用的十分之不熟练... 代码 ...
- Bootstrap页面布局17 - BS选项卡
代码结构: <div class='container-fluid'> <h2 class='page-header'>Bootstrap 选项卡</h2> < ...
- iOS中利用CoreTelephony获取用户当前网络状态(判断2G,3G,4G)
前言: 在项目开发当中,往往需要利用网络.而用户的网络环境也需要我们开发者去注意,根据不同的网络状态作相应的优化,以提升用户体验. 但通常我们只会判断用户是在WIFI还是移动数据,而实际上,移动数据也 ...
- ucenter小结
经历了一天的折腾,大概搞清楚的ucenter接入应用的方法.总结如下: 一.下载安装ucenter.这个很简单. 二.然后就是接入应用. 1.先在你项目的根目录copy一份uc_client文件夹. ...