ini
文件是Initialization File
的縮寫,平時用於存儲軟件的的配置文件。例如:MySQL數據庫的配置文件。
#
代表注釋,[]
代表節點,下面的的所有代表鍵值。
[mysqld] # 節點
# 鍵= 值
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-bin=py-mysql-bin
character-set-server=utf8
collation-server=utf8_general_ci
log-error=/var/log/mysqld.log
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
[mysqld_safe] # 節點
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid
[client] # 節點
# 鍵=值
default-character-set=utf8
這種格式是可以直接使用open
來出來,考慮到自己處理比較麻煩,所以 Python 為我們提供了更為方便的方式。
實例化對象,讀取文件。
# 以下用到的config對象均是此處實例化好的。
import configparser
config = configparser.ConfigParser() # 實例化對象
config.read('my.ini',encoding="utf-8")
import configparser
config = configparser.ConfigParser() # 實例化對象
config.read('my.ini',encoding="utf-8")
# 1.獲取所有節點
result = config.sections()
print(result)
>>> ['mysqld', 'mysqld_safe', 'client']
# 2.獲取節點下的鍵值
result = config.items("mysqld_safe")
print(result)
for key,value in result:
print(key,value)
# 3.獲取某個鍵值
result = config.get("mysqld","collation-server")
print(result)
# 4.檢查是否存在鍵值
v1 = config.has_section("client") # 存在
v2 = config.has_section("clientnot") # 不存在
print(v1,v2)
>>> True False
# 5.添加一個節點
config.add_section("group")# 創建節點
config.set('group',"name","ziqingbaojian") # 給創建的節點添加值
config.set('client',"name","ziqingbaojian") # 給已有的節點添加值
# 此時添加好的節點數據仍然只在內存中,需要將數據寫入到對應的文件中
config.write(open('new.ini',mode='w',encoding='utf-8'))
由圖可得,兩個節點的數據都插入成功,且保存到了新的文件中。
# 5.添加一個節點
config.add_section("group")
config.set('group',"name","ziqingbaojian")
config.set('client',"name","ziqingbaojian")
# config.write(open('new.ini',mode='w',encoding='utf-8'))
config.write(open('my.ini',mode='w',encoding='utf-8'))
保存到已有的文件中,直接進行覆蓋重寫。
# 6.刪除節點
config.remove_section("group")
# 刪除節點中的值
config.remove_option("client",'name')
# 數據寫入內存
config.write(open('new.ini',mode='w',encoding='utf-8'))
說明:本部分不屬於 Python 的內容,屬於 windows 中的知識點。進行簡單的介紹,使用可能較多通常用在寫文檔中。
tree /f > xxx.txt 生成包含所有文件的文件樹
tree > xxx.txt 只包含文件夾,沒有文件
例如:下圖為一個flask的項目獲取它的文件樹只需在終端執行相關的文件即可
tree /f > filepath.txt
E:.
│ filepath.txt
│ manage.py
│
├─.idea
│ │ .gitignore
│ │ flaskBlue.iml
│ │ misc.xml
│ │ modules.xml
│ │ workspace.xml
│ │
│ └─inspectionProfiles
│ profiles_settings.xml
│ Project_Default.xml
│
├─apps
│ │ __init__.py
│ │
│ ├─account
│ │ │ __init__.py
│ │ │
│ │ ├─static
│ │ ├─templates
│ │ │ login.html
│ │ │
│ │ ├─views
│ │ │ │ forget.py
│ │ │ │ user.py
│ │ │ │ __init__.py
│ │ │ │
│ │ │ └─__pycache__
│ │ │ forget.cpython-38.pyc
│ │ │ user.cpython-38.pyc
│ │ │ __init__.cpython-38.pyc
│ │ │
│ │ └─__pycache__
│ │ __init__.cpython-38.pyc
│ │
│ ├─admin
│ │ │ __init__.py
│ │ │
│ │ ├─static
│ │ ├─templates
│ │ ├─views
│ │ │ __init__.py
│ │ │
│ │ └─__pycache__
│ │ __init__.cpython-38.pyc
│ │
│ ├─templates
│ │ login.html
│ │
│ └─__pycache__
│ __init__.cpython-38.pyc
│
└─config
│ settings.py
│ __init__.py
│
└─__pycache__
settings.cpython-38.pyc
__init__.cpython-38.pyc
tree > file.txt # 本命令只顯示文件夾
文件夾 PATH 列表
卷序列號為 53BF-F447
E:.
├─.idea
│ └─inspectionProfiles
├─apps
│ ├─account
│ │ ├─static
│ │ ├─templates
│ │ ├─views
│ │ │ └─__pycache__
│ │ └─__pycache__
│ ├─admin
│ │ ├─static
│ │ ├─templates
│ │ ├─views
│ │ └─__pycache__
│ ├─templates
│ └─__pycache__
└─config
└─__pycache__
可擴展標記語言,是一種簡單的數據存儲語言,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>
注意:在Python開發中用的相對來比較少,作為了解即可(微信支付、微信公眾號消息處理 時會用到基於xml傳輸數據)。
例如:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html
from xml.etree import ElementTree as ET
# ET去打開xml文件
tree = ET.parse("files/xo.xml")
# 獲取根標簽
root = tree.getroot()
print(root) # <Element 'data' at 0x7f94e02763b0>
from xml.etree import ElementTree as ET
content = """ <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="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> """
root = ET.XML(content)
print(root) # <Element 'data' at 0x7fdaa019cea0>
from xml.etree import ElementTree as ET
content = """ <data> <country name="Liechtenstein" id="999" > <rank>2</rank> <year>2023</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Panama"> <rank>69</rank> <year>2026</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country> </data> """
# 獲取根標簽 data
root = ET.XML(content)
country_object = root.find("country")
print(country_object.tag, country_object.attrib)
gdppc_object = country_object.find("gdppc")
print(gdppc_object.tag,gdppc_object.attrib,gdppc_object.text)
from xml.etree import ElementTree as ET
content = """ <data> <country name="Liechtenstein"> <rank>2</rank> <year>2023</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Panama"> <rank>69</rank> <year>2026</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country> </data> """
# 獲取根標簽 data
root = ET.XML(content)
# 獲取data標簽的孩子標簽
for child in root:
# child.tag = conntry
# child.attrib = {"name":"Liechtenstein"}
print(child.tag, child.attrib)
for node in child:
print(node.tag, node.attrib, node.text)
from xml.etree import ElementTree as ET
content = """ <data> <country name="Liechtenstein"> <rank>2</rank> <year>2023</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Panama"> <rank>69</rank> <year>2026</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country> </data> """
root = ET.XML(content)
for child in root.iter('year'):
print(child.tag, child.text)
from xml.etree import ElementTree as ET
content = """ <data> <country name="Liechtenstein"> <rank>2</rank> <year>2023</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Panama"> <rank>69</rank> <year>2026</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country> </data> """
root = ET.XML(content)
v1 = root.findall('country')
print(v1)
v2 = root.find('country').find('rank')
print(v2.text)
from xml.etree import ElementTree as ET
content = """ <data> <country name="Liechtenstein"> <rank>2</rank> <year>2023</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Panama"> <rank>69</rank> <year>2026</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country> </data> """
root = ET.XML(content)
# 修改節點內容和屬性
rank = root.find('country').find('rank')
print(rank.text)
rank.text = "999"
rank.set('update', '2020-11-11')
print(rank.text, rank.attrib)
############ 保存文件 ############
tree = ET.ElementTree(root)
tree.write("new.xml", encoding='utf-8')
# 刪除節點
root.remove( root.find('country') )
print(root.findall('country'))
############ 保存文件 ############
tree = ET.ElementTree(root)
tree.write("newnew.xml", encoding='utf-8')
<home>
<son name="兒1">
<grandson name="兒11"></grandson>
<grandson name="兒12"></grandson>
</son>
<son name="兒2"></son>
</home>
from xml.etree import ElementTree as ET
# 創建根標簽
root = ET.Element("home")
# 創建節點大兒子
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(son2)
tree = ET.ElementTree(root)
tree.write('oooo.xml', encoding='utf-8', short_empty_elements=False)
<famliy>
<son name="兒1">
<grandson name="兒11"></grandson>
<grandson name="兒12"></grandson>
</son>
<son name="兒2"></son>
</famliy>
from xml.etree import ElementTree as ET
# 創建根節點
root = ET.Element("famliy")
# 創建大兒子
son1 = root.makeelement('son', {
'name': '兒1'})
# 創建小兒子
son2 = root.makeelement('son', {
"name": '兒2'})
# 在大兒子中創建兩個孫子
grandson1 = son1.makeelement('grandson', {
'name': '兒11'})
grandson2 = son1.makeelement('grandson', {
'name': '兒12'})
son1.append(grandson1)
son1.append(grandson2)
# 把兒子添加到根節點中
root.append(son1)
root.append(son2)
tree = ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8')
<famliy>
<son name="兒1">
<age name="兒11">孫子</age>
</son>
<son name="兒2"></son>
</famliy>
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")
<user><![CDATA[你好呀]]</user>
from xml.etree import ElementTree as ET
# 創建根節點
root = ET.Element("user")
root.text = "<![CDATA[你好呀]]"
et = ET.ElementTree(root) # 生成文檔對象
et.write("test.xml", encoding="utf-8")
案例:
content = """<xml> <ToUserName><![CDATA[gh_7f083739789a]]></ToUserName> <FromUserName><![CDATA[oia2TjuEGTNoeX76QEjQNrcURxG8]]></FromUserName> <CreateTime>1395658920</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[TEMPLATESENDJOBFINISH]]></Event> <MsgID>200163836</MsgID> <Status><![CDATA[success]]></Status> </xml>"""
from xml.etree import ElementTree as ET
info = {
}
root = ET.XML(content)
for node in root:
# print(node.tag,node.text)
info[node.tag] = node.text
print(info)
繼續努力,終成大器。