首页 > 代码库 > Python学习笔记-2017.5.4thon学习笔记-2017.8.11

Python学习笔记-2017.5.4thon学习笔记-2017.8.11

json pickle 序列化可以dump多次,但是不能load多次的问题
我们可以使用shelve模块
#shelve 模块,是对pickle更上一层的封装
import shelve,datetime
d = shelve.open("shelve模块")
a = {"name":"jack", "job":"it"}
b = [1,2,3,4,5,6]
c = (7,8,9,datetime.datetime.now())
d["a"] = a
d["b"] = b
d["c"] = c
d.close()
print(d.get("a"))
print(d.get("b"))
print(d.get("c"))
# print(d.items())
e = d.items()
for i in e:
    print(i)


#xml
import xml.etree.ElementTree as ET

tree = ET.parse("全国省市.xml")
root = tree.getroot()#取得根目录
print(root)
for child in root:#取得子title
    print(child.tag, child.attrib)#子title属性
    for i in child:
        print(i.tag, i.text)#子title字符
#如上是遍历了所有并并进行打印,下面示例只遍历带某个字段,并进行打印
for node in root.iter("year"):
    print(node.tag,node.attrib, node.text)
#如果有很多层,只能一层一层继续往下遍历,
#修改xml文件
for node in root.iter("year"):
    print(node.tag,node.attrib, node.text)
    newyear = int(node.text) + 1#改为int并加1
    node.text = str(newyear)#重新修改为字符串格式并赋值给year
    node.set("update", "yes")#加入新的属性
tree.write("全国省市2.xml")#也可以写入原文件名字,直接写入原文件。
#删除
for country in root.findall("country"):#找到所有的country节点
    rank = int(country.find("rank").text)
    if rank > 50:
        root.remove("cuntry")
tree.write("xxxxx.xml")#写入
#自己创建xml文档
import xml.etree.ElementTree as ET
new_xml = ET.Element("namelist")#根节点
name = ET.SubElement(new_xml,"name", attrib={"jack": "yes"})#newxml子节点
age = ET.SubElement(name, "age", attrib={"jack":"18"})#name子节点
sex = ET.SubElement(name, "sex")#name子节点
sex.text = "male"#赋值
et = ET.ElementTree(new_xml)#生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True #xml=1.0)#写入文件
ET.dump(new_xml)#生成


#PYyaml,写配置文档使用
#configparser,另外一个编写配置文件
__Author__ = "Jack"
import configparser
config = configparser.ConfigParser()#生成一个config处理对象
config["DEFAULT"] = {"ServerAliveInterval": 45,
                    "Compression":"yes",
                    "CompressionLevel":9}#生成对象并填写类似于字典的key和value
config["bitbucket.org"] = {}#先生成对象
config["bitbucket.org"]["User"] = "hg"#再填写key
config["topsecret.server.com"] ={}
topsecrect = config["topsecret.server.com"]
topsecrect["Host Port"] ="50022"
topsecrect["ForwardX11"] = "no"
config["DEFAULT"]["ForwardX11"] = "yes"
with open("Exzample.ini", "w") as configfile:
    config.write(configfile)

将会生成如下ini配置文件
[DEFAULT]
compression = yes
compressionlevel = 9
serveraliveinterval = 45
forwardx11 = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
host port = 50022
forwardx11 = no
#如上是编写
import configparser
config = configparser.ConfigParser()
config.sections()#
config.read("Exzample.ini")
print(config.sections())#不打印default
print(config.defaults())#打印default,也就是打印所有
print(config["bitbucket.org"]["User"])
#删除
print(config.has_section("bitbucket.org"))#是否存在bitbucket节点

sec = config.remove_section("bitbucket.org")
config.write(open("Test1", "w"))#删除这个节点,并重新写入一个新的Test1文件

 

Python学习笔记-2017.5.4thon学习笔记-2017.8.11