configparser-xml-subprocess-shutil

configparser

1 # 注释1
2 ;  注释2
3  
4 [section1] # 节点
5 k1 = v1    # 值
6 k2:v2       # 值
7  
8 [section2] # 节点
9 k1 = v1    # 值

 

 

1.获取所有节点

import configparser

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

 

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

import configparser

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

 

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

import configparser

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

 

4.获取指定节点下指定key

import configparser

config = configparser.ConfigParser()
config.read('b.txt',encoding='utf-8')

v = config.get('section1','k1')
#v1 = config.getint('section1','k1')
#v2 = config.getfloat('section1','k1')
#v3 = config.getboolean('section1','k1')

print(v)

 

5.检查 删除 添加节点

import configparser

config = configparser.ConfigParser()
config.read('b.txt',encoding='utf-8')

检查

has_sec = config.has_section('section1')
print(has_sec)

添加节点

config.add_section("SEC-1")
config.write(open('b.txt','w'))

删除节点

config.remove_section("SEC-1")
config.write(open('b.txt','w'))

 


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

import configparser

config = configparser.ConfigParser()
config.read('b.txt',encoding='utf-8')

检查

has_opt = config.has_option('section1','k1')
print(has_opt)

删除

config.remove_option('section1','k1')
config.write(open('b.txt','w'))

设置

config.set('section1','k10','123')
config.write(open('b.txt','w'))

xml

 1 <data>
 2     <country name="Liechtenstein">
 3         <rank updated="yes">2</rank>
 4         <year>2023</year>
 5         <gdppc>141100</gdppc>
 6         <neighbor direction="E" name="Austria" />
 7         <neighbor direction="W" name="Switzerland" />
 8     </country>
 9     <country name="Singapore">
10         <rank updated="yes">5</rank>
11         <year>2026</year>
12         <gdppc>59900</gdppc>
13         <neighbor direction="N" name="Malaysia" />
14     </country>
15     <country name="Panama">
16         <rank updated="yes">69</rank>
17         <year>2026</year>
18         <gdppc>13600</gdppc>
19         <neighbor direction="W" name="Costa Rica" />
20         <neighbor direction="E" name="Colombia" />
21     </country>
22 </data>

 

1.利用ElementTree.XML将字符串解析成xml对象

from xml.etree import ElementTree as ET

str_xml = open('name.xml','r').read()    #打开文件 读取xml内容

root = ET.XML(str_xml)     #获取xml文件根节点

 

2.利用ElementTree.parse将文件直接解析成xml对象

from xml.etree import ElementTree as ET

tree = ET.parse('name.xml')    #直接解析xml文件

root = tree.getroot()    #获取xml文件根节点

 

print(root.tag)    #获取顶层标签

 

3.遍历xml文档的第二层

for child in root:
print(child.tag, child.attrib)  # 第二层节点的标签和标签属性

for i in child:           #遍历xml文档的第三层
print(i.tag,i.text)     #第二层节点的标签名称和内容

 

修改设置删除

1.from xml.etree import ElementTree as ET

str_xml = open('name.xml','r').read()    #打开文件 读取xml内容

root = ET.XML(str_xml)  #将字符串解析成xml特殊对象 root代指xml文件的根节点

for node in root.iter('year'):      #循环所有的year节点
new_year = int(node.text) + 1    #将year节点中的内容自增一
node.text = str(new_year)

node.set('name', 'alex')   #设置属性
node.set('age', '18')
del node.attrib['name']   #删除属性

tree = ET.ElementTree(root)      
tree.write("new.xml",encoding='utf-8'    #保存文件

 

2.from xml.etree import ElementTree as ET

tree = ET.parse("name.xml")  #直接解析xml文

root = tree.getroot()  #获取xml文件的根节点

for node in root.iter('year'):  #循环所有的year节点
new_year = int(node.text) + 1  #将year节点中的内容自增一
node.text = str(new_year)

node.set('name','alex')  #设置属性
node.set('age','18')

del node.attrib['name']  #删除属性

tree.write("new.xml",encoding='utf-8') #保存文件

 

3.from xml.etree import ElementTree as ET

str_xml = open('name.xml','r').read()
root = ET.XML(str_xml)

for country in root.findall('country'):    #遍历data下的所有country节点
rank = int(country.find('rank').text)  #获取每一个country节点下rank节点的内容
if rank > 50:
root.remove(country)   #删除指定country节点

tree = ET.ElementTree(root)
tree.write("newnew.xml",encoding='utf-8'

from xml.etree import ElementTree as ET
tree = ET.parse('name.xml')
root = tree.getroot()

 

4.for country in root.findall('counrty'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)

tree.write('new.xml',encoding='utf-8')

 

4.创建XML文档

1.from xml.etree import ElementTree as ET

#创建节点
root = ET.Element('famliy')

#创建节点儿子
son1 = ET.Element('son',{'name':'erzi1'})
son2 = ET.Element('son',{'name':'erzi2'})

#创建孙子
grandson1 = ET.Element('grandson',{'name':'erzi11'})
grandson2 = ET.Element('randson',{'name':'erzi12'})

#把添加到很节点中
root.append(son1)
root.append(son2)

tree = ET.ElementTree(root)
tree.write('text.xml',encoding='utf-8',short_empty_elements=False)

 

2.fom xml.etree import ElementTree as ET

#创建根节点
root = ET.Element('famliy')

# 创建大儿子
son1 = root.makeelement('son',{'name':'erzi1'})
# 创建小儿子
son2 = root.makeelement('son',{'name':'erzi2'})

# 在大儿子中创建两个孙子
grandson1 = son1.makeelement('grangdson',{'name':'erzi11'})
grandson2 = son1.makeelement('grandson',{'name':'erzi12'})

son1.append(grandson1)
son1.append(grandson2)

# 把儿子添加到根节点中
root.append(son1)
root.append(son2)

tree = ET.ElementTree(root)
tree.write('test1.xml',encoding='utf-8',short_empty_elements=False)

 

3.from xml.etree import ElementTree as ET

# 创建根节点
root = ET.Element('famliy')

# 创建节点大儿子
son1 = ET.SubElement(root,'son',attrib={'name':'erzi1'})
# 创建小儿子
son2 = ET.SubElement(root,'son',attrib={'name':'erzi2'})

# 在大儿子中创建一个孙子
grandson1 = ET.SubElement(son1,"age",attrib={'name':'erzi11'})
grandson1.text = "孙子"

#生成文档对象

et = ET.ElementTree(root) 
et.write('test2.xml',encoding='utf-8',xml_declaration=True,short_empty_elements=False)

 

5.创建缩进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 = root.makeelement('son',{'name':'erzi1'})
# 创建小儿子
son2 = root.makeelement('son',{'name':'erzi2'})

# 在大儿子中创建两个孙子

grandson1 = son1.makeelement('grandson',{'name':'erzi11'})
grandson2 = son1.makeelement('rangdson',{'name':'erzi12'})

son1.append(grandson1)
son1.append(grandson2)

# 把儿子添加到根节点中
root.append(son1)
root.append(son1)

raw_str = prettify(root) #换行

f = open('test66.xml','w',encoding='utf-8')
f.write(raw_str)
f.close()

subprocess

call 

执行命令,返回状态码

import subprocess

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

 

check_call  

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

subprocess.check_call(["ls", "-l"])
subprocess.check_call("exit 1", shell=True)

check_output

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

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

subprocess.Popen(...)

用于执行复杂的系统命令

import subprocess
ret1 = subprocess.Popen(["mkdir","t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)

 

import subprocess

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

 

 1 1.
 2 import subprocess
 3 
 4 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
 5 obj.stdin.write("print(1)\n")
 6 obj.stdin.write("print(2)")
 7 obj.stdin.close()
 8 
 9 cmd_out = obj.stdout.read()
10 obj.stdout.close()
11 cmd_error = obj.stderr.read()
12 obj.stderr.close()
13 
14 print(cmd_out)
15 print(cmd_error)
16 
17 2.
18 import subprocess
19 
20 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
21 obj.stdin.write("print(1)\n")
22 obj.stdin.write("print(2)")
23 
24 out_error_list = obj.communicate()
25 print(out_error_list)
26 
27 
28 3.
29 import subprocess
30 
31 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
32 out_error_list = obj.communicate('print("hello")')
33 print(out_error_list)

shutil

高级的 文件、文件夹、压缩包 处理模块

import shutil

ret = shutil.make_archive('testi', 'gztar', root_dir='/root/')


把文件压缩到/mnt/下面

ret1 = shutil.make_archive("/mnt/test2", "zip", root_dir="/root/han") 

 

zipfile 

压缩

import zipfile

z = zipfile.ZipFile("laxi.zip",'w')
z.write('a.log')
z.write("b.log")
z.close()

解压

z = zipfile.ZipFile('laxi.zip','r')
z.extractall()
z.close() 

解压指定文件
z = zipfile.ZipFile('laxi.zip','r')
z.extract("a.log")
z.close()

 

tarfile

import tarfile
tar = tarfile.open("your.tar","w")
tar.add('/root/han/bbs2.log', arcname='bbs2.log')
tar.add('/root/han/cmddb.log', arcname='cmddb.log')
tar.close()

 解压

import tarfile

tar = tarfile.open('your.tar','r')
tar.extractall() # 可设置解压地址
tar.close()

解压指定文件
tar = tarfile.open('your.tar','r')
obj = tar.getmember("cmddb.log")
tar.extract(obj)
tar.close()

 

 

posted @ 2017-01-12 23:30  ༺༽秋水.无痕༼༻  阅读(178)  评论(0编辑  收藏  举报
……