1. 程式人生 > >Python學習筆記-2017.5.4thon學習筆記-2017.8.11

Python學習筆記-2017.5.4thon學習筆記-2017.8.11

count 一個 iter section 對象 port pytho 多次 pyyaml

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