python模組(shelve,xml,configparser,hashlib,logging)
阿新 • • 發佈:2018-12-24
1.1shelve模組
shelve 模組比pickle模組簡單,只有一個open函式,返回類似字典物件,可讀可寫:key必須為字串,
而值可以是python所支援的資料型別。
shelve模組主要用來儲存一個簡單的資料,
shelve最重要的函式是open,在呼叫它的時候,使用檔名作為引數,它會返回一個架子(shelf)物件,可以用它來儲存類容。
1 f = shelve.open(r"shelve_test.txt") 2 # aa = {"stu1":{"name":"yj","age":19}, 3 # "stu2":{"name": "lq", "age": 20}shelve測試4 # } 類似這種方式寫入到檔案 5 6 # f["stu1"] = {"name":"yj","age":19} 7 # f["stu2"] = {"name":"yj","age":19} 8 print(f.get("stu1")["age"]) 9 print(f.get("stu2"))
1.2xml模組
xml是實現不同語言程式之間進行資料交換的協議,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.解析XML
1 from xml.etree import ElementTree as ET 2 3 4 # 開啟檔案,讀取XML內容 5 str_xml = open('xo.xml', 'r').read() 6 7 # 將字串解析成xml特殊物件,root代指xml檔案的根節點 8 root = ET.XML(str_xml)利用ElementTree.XML將字串解析成xml物件
1 from xml.etree import ElementTree as ET 2 3 # 直接解析xml檔案 4 tree = ET.parse("xo.xml") 5 6 # 獲取xml檔案的根節點 7 root = tree.getroot()利用ElementTree.parse將檔案直接解析成xml物件
2.操作xml
XML格式型別是節點巢狀節點,對於每一個節點均有以下功能,以便對當前節點進行操作
1 class Element: 2 """An XML element. 3 4 This class is the reference implementation of the Element interface. 5 6 An element's length is its number of subelements. That means if you 7 want to check if an element is truly empty, you should check BOTH 8 its length AND its text attribute. 9 10 The element tag, attribute names, and attribute values can be either 11 bytes or strings. 12 13 *tag* is the element name. *attrib* is an optional dictionary containing 14 element attributes. *extra* are additional element attributes given as 15 keyword arguments. 16 17 Example form: 18 <tag attrib>text<child/>...</tag>tail 19 20 """ 21 22 當前節點的標籤名 23 tag = None 24 """The element's name.""" 25 26 當前節點的屬性 27 28 attrib = None 29 """Dictionary of the element's attributes.""" 30 31 當前節點的內容 32 text = None 33 """ 34 Text before first subelement. This is either a string or the value None. 35 Note that if there is no text, this attribute may be either 36 None or the empty string, depending on the parser. 37 38 """ 39 40 tail = None 41 """ 42 Text after this element's end tag, but before the next sibling element's 43 start tag. This is either a string or the value None. Note that if there 44 was no text, this attribute may be either None or an empty string, 45 depending on the parser. 46 47 """ 48 49 def __init__(self, tag, attrib={}, **extra): 50 if not isinstance(attrib, dict): 51 raise TypeError("attrib must be dict, not %s" % ( 52 attrib.__class__.__name__,)) 53 attrib = attrib.copy() 54 attrib.update(extra) 55 self.tag = tag 56 self.attrib = attrib 57 self._children = [] 58 59 def __repr__(self): 60 return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self)) 61 62 def makeelement(self, tag, attrib): 63 建立一個新節點 64 """Create a new element with the same type. 65 66 *tag* is a string containing the element name. 67 *attrib* is a dictionary containing the element attributes. 68 69 Do not call this method, use the SubElement factory function instead. 70 71 """ 72 return self.__class__(tag, attrib) 73 74 def copy(self): 75 """Return copy of current element. 76 77 This creates a shallow copy. Subelements will be shared with the 78 original tree. 79 80 """ 81 elem = self.makeelement(self.tag, self.attrib) 82 elem.text = self.text 83 elem.tail = self.tail 84 elem[:] = self 85 return elem 86 87 def __len__(self): 88 return len(self._children) 89 90 def __bool__(self): 91 warnings.warn( 92 "The behavior of this method will change in future versions. " 93 "Use specific 'len(elem)' or 'elem is not None' test instead.", 94 FutureWarning, stacklevel=2 95 ) 96 return len(self._children) != 0 # emulate old behaviour, for now 97 98 def __getitem__(self, index): 99 return self._children[index] 100 101 def __setitem__(self, index, element): 102 # if isinstance(index, slice): 103 # for elt in element: 104 # assert iselement(elt) 105 # else: 106 # assert iselement(element) 107 self._children[index] = element 108 109 def __delitem__(self, index): 110 del self._children[index] 111 112 def append(self, subelement): 113 為當前節點追加一個子節點 114 """Add *subelement* to the end of this element. 115 116 The new element will appear in document order after the last existing 117 subelement (or directly after the text, if it's the first subelement), 118 but before the end tag for this element. 119 120 """ 121 self._assert_is_element(subelement) 122 self._children.append(subelement) 123 124 def extend(self, elements): 125 為當前節點擴充套件 n 個子節點 126 """Append subelements from a sequence. 127 128 *elements* is a sequence with zero or more elements. 129 130 """ 131 for element in elements: 132 self._assert_is_element(element) 133 self._children.extend(elements) 134 135 def insert(self, index, subelement): 136 在當前節點的子節點中插入某個節點,即:為當前節點建立子節點,然後插入指定位置 137 """Insert *subelement* at position *index*.""" 138 self._assert_is_element(subelement) 139 self._children.insert(index, subelement) 140 141 def _assert_is_element(self, e): 142 # Need to refer to the actual Python implementation, not the 143 # shadowing C implementation. 144 if not isinstance(e, _Element_Py): 145 raise TypeError('expected an Element, not %s' % type(e).__name__) 146 147 def remove(self, subelement): 148 在當前節點在子節點中刪除某個節點 149 """Remove matching subelement. 150 151 Unlike the find methods, this method compares elements based on 152 identity, NOT ON tag value or contents. To remove subelements by 153 other means, the easiest way is to use a list comprehension to 154 select what elements to keep, and then use slice assignment to update 155 the parent element. 156 157 ValueError is raised if a matching element could not be found. 158 159 """ 160 # assert iselement(element) 161 self._children.remove(subelement) 162 163 def getchildren(self): 164 獲取所有的子節點(廢棄) 165 """(Deprecated) Return all subelements. 166 167 Elements are returned in document order. 168 169 """ 170 warnings.warn( 171 "This method will be removed in future versions. " 172 "Use 'list(elem)' or iteration over elem instead.", 173 DeprecationWarning, stacklevel=2 174 ) 175 return self._children 176 177 def find(self, path, namespaces=None): 178 獲取第一個尋找到的子節點 179 """Find first matching element by tag name or path. 180 181 *path* is a string having either an element tag or an XPath, 182 *namespaces* is an optional mapping from namespace prefix to full name. 183 184 Return the first matching element, or None if no element was found. 185 186 """ 187 return ElementPath.find(self, path, namespaces) 188 189 def findtext(self, path, default=None, namespaces=None): 190 獲取第一個尋找到的子節點的內容 191 """Find text for first matching element by tag name or path. 192 193 *path* is a string having either an element tag or an XPath, 194 *default* is the value to return if the element was not found, 195 *namespaces* is an optional mapping from namespace prefix to full name. 196 197 Return text content of first matching element, or default value if 198 none was found. Note that if an element is found having no text 199 content, the empty string is returned. 200 201 """ 202 return ElementPath.findtext(self, path, default, namespaces) 203 204 def findall(self, path, namespaces=None): 205 獲取所有的子節點 206 """Find all matching subelements by tag name or path. 207 208 *path* is a string having either an element tag or an XPath, 209 *namespaces* is an optional mapping from namespace prefix to full name. 210 211 Returns list containing all matching elements in document order. 212 213 """ 214 return ElementPath.findall(self, path, namespaces) 215 216 def iterfind(self, path, namespaces=None): 217 獲取所有指定的節點,並建立一個迭代器(可以被for迴圈) 218 """Find all matching subelements by tag name or path. 219 220 *path* is a string having either an element tag or an XPath, 221 *namespaces* is an optional mapping from namespace prefix to full name. 222 223 Return an iterable yielding all matching elements in document order. 224 225 """ 226 return ElementPath.iterfind(self, path, namespaces) 227 228 def clear(self): 229 清空節點 230 """Reset element. 231 232 This function removes all subelements, clears all attributes, and sets 233 the text and tail attributes to None. 234 235 """ 236 self.attrib.clear() 237 self._children = [] 238 self.text = self.tail = None 239 240 def get(self, key, default=None): 241 獲取當前節點的屬性值 242 """Get element attribute. 243 244 Equivalent to attrib.get, but some implementations may handle this a 245 bit more efficiently. *key* is what attribute to look for, and 246 *default* is what to return if the attribute was not found. 247 248 Returns a string containing the attribute value, or the default if 249 attribute was not found. 250 251 """ 252 return self.attrib.get(key, default) 253 254 def set(self, key, value): 255 為當前節點設定屬性值 256 """Set element attribute. 257 258 Equivalent to attrib[key] = value, but some implementations may handle 259 this a bit more efficiently. *key* is what attribute to set, and 260 *value* is the attribute value to set it to. 261 262 """ 263 self.attrib[key] = value 264 265 def keys(self): 266 獲取當前節點的所有屬性的 key 267 268 """Get list of attribute names. 269 270 Names are returned in an arbitrary order, just like an ordinary 271 Python dict. Equivalent to attrib.keys() 272 273 """ 274 return self.attrib.keys() 275 276 def items(self): 277 獲取當前節點的所有屬性值,每個屬性都是一個鍵值對 278 """Get element attributes as a sequence. 279 280 The attributes are returned in arbitrary order. Equivalent to 281 attrib.items(). 282 283 Return a list of (name, value) tuples. 284 285 """ 286 return self.attrib.items() 287 288 def iter(self, tag=None): 289 在當前節點的子孫中根據節點名稱尋找所有指定的節點,並返回一個迭代器(可以被for迴圈)。 290 """Create tree iterator. 291 292 The iterator loops over the element and all subelements in document 293 order, returning all elements with a matching tag. 294 295 If the tree structure is modified during iteration, new or removed 296 elements may or may not be included. To get a stable set, use the 297 list() function on the iterator, and loop over the resulting list. 298 299 *tag* is what tags to look for (default is to return all elements) 300 301 Return an iterator containing all the matching elements. 302 303 """ 304 if tag == "*": 305 tag = None 306 if tag is None or self.tag == tag: 307 yield self 308 for e in self._children: 309 yield from e.iter(tag) 310 311 # compatibility 312 def getiterator(self, tag=None): 313 # Change for a DeprecationWarning in 1.4 314 warnings.warn( 315 "This method will be removed in future versions. " 316 "Use 'elem.iter()' or 'list(elem.iter())' instead.", 317 PendingDeprecationWarning, stacklevel=2 318 ) 319 return list(self.iter(tag)) 320 321 def itertext(self): 322 在當前節點的子孫中根據節點名稱尋找所有指定的節點的內容,並返回一個迭代器(可以被for迴圈)。 323 """Create text iterator. 324 325 The iterator loops over the element and all subelements in document 326 order, returning all inner text. 327 328 """ 329 tag = self.tag 330 if not isinstance(tag, str) and tag is not None: 331 return 332 if self.text: 333 yield self.text 334 for e in self: 335 yield from e.itertext() 336 if e.tail: 337 yield e.tailxml的語法功能
由於每個節點都具有以上的方法,並且在上一步驟中解析時均得到了root(xml檔案的根節點),so 可以利用以上方法進行操作xml檔案。
a.遍歷xml文件的所有內容
1 from xml.etree import ElementTree as ET 2 3 ############ 解析方式一 ############ 4 """ 5 # 開啟檔案,讀取XML內容 6 str_xml = open('xo.xml', 'r').read() 7 8 # 將字串解析成xml特殊物件,root代指xml檔案的根節點 9 root = ET.XML(str_xml) 10 """ 11 ############ 解析方式二 ############ 12 13 # 直接解析xml檔案 14 tree = ET.parse("xo.xml") 15 16 # 獲取xml檔案的根節點 17 root = tree.getroot() 18 19 20 ### 操作 21 22 # 頂層標籤 23 print(root.tag) 24 25 26 # 遍歷XML文件的第二層 27 for child in root: 28 # 第二層節點的標籤名稱和標籤屬性 29 print(child.tag, child.attrib) 30 # 遍歷XML文件的第三層 31 for i in child: 32 # 第二層節點的標籤名稱和內容 33 print(i.tag,i.text)View Code
b.遍歷XML中指定的節點
1 from xml.etree import ElementTree as ET 2 3 ############ 解析方式一 ############ 4 """ 5 # 開啟檔案,讀取XML內容 6 str_xml = open('xo.xml', 'r').read() 7 8 # 將字串解析成xml特殊物件,root代指xml檔案的根節點 9 root = ET.XML(str_xml) 10 """ 11 ############ 解析方式二 ############ 12 13 # 直接解析xml檔案 14 tree = ET.parse("xo.xml") 15 16 # 獲取xml檔案的根節點 17 root = tree.getroot() 18 19 20 ### 操作 21 22 # 頂層標籤 23 print(root.tag) 24 25 26 # 遍歷XML中所有的year節點 27 for node in root.iter('year'): 28 # 節點的標籤名稱和內容 29 print(node.tag, node.text)View Code
c.修改節點內容
由於修改的節點時,均是在記憶體中進行,其不會影響檔案中的內容。所以,如果想要修改,則需要重新將記憶體中的內容寫到檔案。
1 from xml.etree import ElementTree as ET 2 3 ############ 解析方式一 ############ 4 5 # 開啟檔案,讀取XML內容 6 str_xml = open('xo.xml', 'r').read() 7 8 # 將字串解析成xml特殊物件,root代指xml檔案的根節點 9 root = ET.XML(str_xml) 10 11 ############ 操作 ############ 12 13 # 頂層標籤 14 print(root.tag) 15 16 # 迴圈所有的year節點 17 for node in root.iter('year'): 18 # 將year節點中的內容自增一 19 new_year = int(node.text) + 1 20 node.text = str(new_year) 21 22 # 設定屬性 23 node.set('name', 'alex') 24 node.set('age', '18') 25 # 刪除屬性 26 del node.attrib['name'] 27 28 29 ############ 儲存檔案 ############ 30 tree = ET.ElementTree(root) 31 tree.write("newnew.xml", encoding='utf-8')解析字串方式,修改,儲存
1 from xml.etree import ElementTree as ET 2 3 ############ 解析方式二 ############ 4 5 # 直接解析xml檔案 6 tree = ET.parse("xo.xml") 7 8 # 獲取xml檔案的根節點 9 root = tree.getroot() 10 11 ############ 操作 ############ 12 13 # 頂層標籤 14 print(root.tag) 15 16 # 迴圈所有的year節點 17 for node in root.iter('year'): 18 # 將year節點中的內容自增一 19 new_year = int(node.text) + 1 20 node.text = str(new_year) 21 22 # 設定屬性 23 node.set('name', 'alex') 24 node.set('age', '18') 25 # 刪除屬性 26 del node.attrib['name'] 27 28 29 ############ 儲存檔案 ############ 30 tree.write("newnew.xml", encoding='utf-8')解析2
d.刪除節點
1 from xml.etree import ElementTree as ET 2 3 ############ 解析字串方式開啟 ############ 4 5 # 開啟檔案,讀取XML內容 6 str_xml = open('xo.xml', 'r').read() 7 8 # 將字串解析成xml特殊物件,root代指xml檔案的根節點 9 root = ET.XML(str_xml) 10 11 ############ 操作 ############ 12 13 # 頂層標籤 14 print(root.tag) 15 16 # 遍歷data下的所有country節點 17 for country in root.findall('country'): 18 # 獲取每一個country節點下rank節點的內容 19 rank = int(country.find('rank').text) 20 21 if rank > 50: 22 # 刪除指定country節點 23 root.remove(country) 24 25 ############ 儲存檔案 ############ 26 tree = ET.ElementTree(root) 27 tree.write("newnew.xml", encoding='utf-8')解析字串方式開啟,刪除,儲存
1 from xml.etree import ElementTree as ET 2 3 ############ 解析字串方式開啟 ############ 4 5 # 開啟檔案,讀取XML內容 6 str_xml = open('xo.xml', 'r').read() 7 8 # 將字串解析成xml特殊物件,root代指xml檔案的根節點 9 root = ET.XML(str_xml) 10 11 ############ 操作 ############ 12 13 # 頂層標籤 14 print(root.tag) 15 16 # 遍歷data下的所有country節點 17 for country in root.findall('country'): 18 # 獲取每一個country節點下rank節點的內容 19 rank = int(country.find('rank').text) 20 21 if rank > 50: 22 # 刪除指定country節點 23 root.remove(country) 24 25 ############ 儲存檔案 ############ 26 tree = ET.ElementTree(root) 27 tree.write("newnew.xml", encoding='utf-8')解析2
3.建立xml
1 from xml.etree import ElementTree as ET 2 3 4 # 建立根節點 5 root = ET.Element("famliy") 6 7 8 # 建立節點大兒子 9 son1 = ET.Element('son', {'name': '兒1'}) 10 # 建立小兒子 11 son2 = ET.Element('son', {"name": '兒2'}) 12 13 # 在大兒子中建立兩個孫子 14 grandson1 = ET.Element('grandson', {'name': '兒11'}) 15 grandson2 = ET.Element('grandson', {'name': '兒12'}) 16 son1.append(grandson1) 17 son1.append(grandson2) 18 19 20 # 把兒子新增到根節點中 21 root.append(son1) 22 root.append(son1) 23 24 tree = ET.ElementTree(root) 25 tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)方式一
1 from xml.etree import ElementTree as ET 2 3 # 建立根節點 4 root = ET.Element("famliy") 5 6 7 # 建立大兒子 8 # son1 = ET.Element('son', {'name': '兒1'}) 9 son1 = root.makeelement('son', {'name': '兒1'}) 10 # 建立小兒子 11 # son2 = ET.Element('son', {"name": '兒2'}) 12 son2 = root.makeelement('son', {"name": '兒2'}) 13 14 # 在大兒子中建立兩個孫子 15 # grandson1 = ET.Element('grandson', {'name': '兒11'}) 16 grandson1 = son1.makeelement('grandson', {'name': '兒11'}) 17 # grandson2 = ET.Element('grandson', {'name': '兒12'}) 18 grandson2 = son1.makeelement('grandson', {'name': '兒12'}) 19 20 son1.append(grandson1) 21 son1.append(grandson2) 22 23 24 # 把兒子新增到根節點中 25 root.append(son1) 26 root.append(son1) 27 28 tree = ET.ElementTree(root) 29 tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)方式二
1 from xml.etree import ElementTree as ET 2 3 4 # 建立根節點 5 root = ET.Element("famliy") 6 7 8 # 建立節點大兒子 9 son1 = ET.SubElement(root, "son", attrib={'name': '兒1'}) 10 # 建立小兒子 11 son2 = ET.SubElement(root, "son", attrib={"name": "兒2"}) 12 13 # 在大兒子中建立一個孫子 14 grandson1 = ET.SubElement(son1, "age", attrib={'name': '兒11'}) 15 grandson1.text = '孫子' 16 17 18 et = ET.ElementTree(root) #生成文件物件 19 et.write("test.xml", encoding="utf-8", xml_declaration=True, short_empty_elements=False)方式三
原生儲存的xml是預設無縮排,如果要設定縮排的話,需要修改儲存方式:
1 from xml.etree import ElementTree as ET 2 from xml.dom import minidom 3 4 5 def prettify(elem): 6 """將節點轉換成字串,並新增縮排。 7 """ 8 rough_string = ET.tostring(elem, 'utf-8') 9 reparsed = minidom.parseString(rough_string) 10 return reparsed.toprettyxml(indent="\t") 11 12 # 建立根節點 13 root = ET.Element("famliy") 14 15 16 # 建立大兒子 17 # son1 = ET.Element('son', {'name': '兒1'}) 18 son1 = root.makeelement('son', {'name': '兒1'}) 19 # 建立小兒子 20 # son2 = ET.Element('son', {"name": '兒2'}) 21 son2 = root.makeelement('son', {"name": '兒2'}) 22 23 # 在大兒子中建立兩個孫子 24 # grandson1 = ET.Element('grandson', {'name': '兒11'}) 25 grandson1 = son1.makeelement('grandson', {'name': '兒11'}) 26 # grandson2 = ET.Element('grandson', {'name': '兒12'}) 27 grandson2 = son1.makeelement('grandson', {'name': '兒12'}) 28 29 son1.append(grandson1) 30 son1.append(grandson2) 31 32 33 # 把兒子新增到根節點中 34 root.append(son1) 35 root.append(son1) 36 37 38 raw_str = prettify(root) 39 40 f = open("xxxoo.xml",'w',encoding='utf-8') 41 f.write(raw_str) 42 f.close()View Code
xml教程的:點選
1.3configparser模組
configparser主要用於配置檔案分析用的
configparser用於處理特定格式的檔案,本質上是利用open來操作檔案
1 # 註釋1 2 ; 註釋2 3 4 [section1] # 節點 5 k1 = v1 # 值 6 k2:v2 # 值 7 8 [section2] # 節點 9 k1 = v1 # 值 10 11 #註釋檔案格式
我用linux的yum.conf做測試
1 [main] 2 cachedir=/var/cache/yum/$basearch/$releasever 3 keepcache=0 4 debuglevel=2 5 logfile=/var/log/yum.log 6 exactarch=1 7 obsoletes=1 8 gpgcheck=1 9 plugins=1 10 installonly_limit=5 11 bugtracker_url=http://bugs.centos.org/set_project.php?project_id=23&ref=http://bugs.centos.org/bug_report_page.php?category=yum 12 distroverpkg=centos-release 13 14 15 # This is the default, if you make this bigger yum won't see if the metadata 16 # is newer on the remote and so you'll "gain" the bandwidth of not having to 17 # download the new metadata and "pay" for it by yum not having correct 18 # information. 19 # It is esp. important, to have correct metadata, for distributions like 20 # Fedora which don't keep old packages around. If you don't like this checking 21 # interupting your command line usage, it's much better to have something 22 # manually check the metadata once an hour (yum-updatesd will do this). 23 # metadata_expire=90m 24 25 # PUT YOUR REPOS HERE OR IN separate files named file.repo 26 # in /etc/yum.repos.dyum.conf
1.獲取所有節點
1 import configparser 2 config = configparser.ConfigParser() 3 config.read('yum.conf', encoding='utf-8') 4 ret = config.sections() 5 print(ret)獲取子節點
2.獲取指定節點下所有的鍵值對
1 config = configparser.ConfigParser() 2 config.read('yum.conf', encoding='utf-8') 3 ret = config.items('main') 4 for i in ret: 5 print(i)鍵值對
3.獲取指定節點下所有的鍵
1 config = configparser.ConfigParser() 2 config.read('yum.conf', encoding='utf-8') 3 ret = config.options('main')#獲取節點下的所有鍵 4 for i in ret: 5 print(i)獲取鍵
4。獲取指定鍵的值
1 config = configparser.ConfigParser() 2 config.read('yum.conf', encoding='utf-8') 3 4 v = config.get('main', 'cachedir') #/var/cache/yum/$basearch/$releasever 5 v1 = config.getint('main', 'keepcache') #0 6 7 8 print(v) 9 print(v1)獲取指定key的值
5.檢查,刪除,新增節點
1 config = configparser.ConfigParser() 2 config.read('yum.conf', encoding='utf-8') 3 4 # 檢查 5 has_sec = config.has_section('main