python 学习 [day6]
遞歸階乘:
函數(shù)自己調(diào)用自己循環(huán)操作的模式稱(chēng)之為遞歸
def func(num):if num == 1:return 1return num * func(num - 1)print(func(7)) 遞歸階乘反射:
含義:通過(guò)字符串的形式去對(duì)象(模塊)中操作(尋找/檢查/刪除/設(shè)置)成員
通過(guò)字符串形式調(diào)用模塊方法 使用getattr()
通過(guò)字符串形式調(diào)用模塊 采用__import__("inp", fromlist=Ture) ?fromlist參數(shù)傳輸什么路徑就倒入什么路徑,如果沒(méi)有該參數(shù),將無(wú)法導(dǎo)入inp.account類(lèi)型
hasattr(對(duì)象, 字符串) 檢查對(duì)象中是否存在匹配字符串的方法,存在 返回True 不存在返回Falsefunc = getattr(對(duì)象, 字符串) 將對(duì)象中匹配字符串的函數(shù)體賦值給func對(duì)象,在通過(guò)func()執(zhí)行函數(shù)setattr(對(duì)象, 字符串, 值) 在對(duì)象中插入函數(shù)delattr(對(duì)象, 字符串) 刪除對(duì)象中字符串匹配的函數(shù)體 #run函數(shù) 根據(jù)用戶(hù)輸入(commands/login),完成倒入commands模塊并執(zhí)行l(wèi)ogin方法; def run():inp = input("請(qǐng)輸入要訪(fǎng)問(wèn)的url")m, f = inp.split("/")if hasattr(m, f):func = getattr(m, f)func()else:print('404') 字符串調(diào)用函數(shù)?
模塊中的特殊變量
__name__ #當(dāng)執(zhí)行當(dāng)前文件時(shí)當(dāng)前文件的特殊變量__name__ == '__main__',否則__name__不等于__main____file__ #獲取當(dāng)前之行腳本的相對(duì)路徑os.path.abspath(__file__) #獲取文件的絕對(duì)路徑os.path.dirname("dir/file") #文件或目錄的上級(jí)目錄sys模塊
sys.argv 命令行參數(shù)List,第一個(gè)元素是程序本身路徑 sys.exit(n) 退出程序,正常退出時(shí)exit(0) sys.version 獲取Python解釋程序的版本信息 sys.maxint 最大的Int值 sys.path 返回模塊的搜索路徑,初始化時(shí)使用PYTHONPATH環(huán)境變量的值 sys.platform 返回操作系統(tǒng)平臺(tái)名稱(chēng) sys.stdin 輸入相關(guān) sys.stdout 輸出相關(guān) sys.stderror 錯(cuò)誤相關(guān)os模塊
os.getcwd() 獲取當(dāng)前工作目錄,即當(dāng)前python腳本工作的目錄路徑 os.chdir("dirname") 改變當(dāng)前腳本工作目錄;相當(dāng)于shell下cd os.curdir 返回當(dāng)前目錄: ('.') os.pardir 獲取當(dāng)前目錄的父目錄字符串名:('..') os.makedirs('dir1/dir2') 可生成多層遞歸目錄 os.removedirs('dirname1') 若目錄為空,則刪除,并遞歸到上一級(jí)目錄,如若也為空,則刪除,依此類(lèi)推 os.mkdir('dirname') 生成單級(jí)目錄;相當(dāng)于shell中mkdir dirname os.rmdir('dirname') 刪除單級(jí)空目錄,若目錄不為空則無(wú)法刪除,報(bào)錯(cuò);相當(dāng)于shell中rmdir dirname os.listdir('dirname') 列出指定目錄下的所有文件和子目錄,包括隱藏文件,并以列表方式打印 os.remove() 刪除一個(gè)文件 os.rename("oldname","new") 重命名文件/目錄 os.stat('path/filename') 獲取文件/目錄信息 os.sep 操作系統(tǒng)特定的路徑分隔符,win下為"\\",Linux下為"/" os.linesep 當(dāng)前平臺(tái)使用的行終止符,win下為"\t\n",Linux下為"\n" os.pathsep 用于分割文件路徑的字符串 os.name 字符串指示當(dāng)前使用平臺(tái)。win->'nt'; Linux->'posix' os.system("bash command") 運(yùn)行shell命令,直接顯示 os.environ 獲取系統(tǒng)環(huán)境變量 os.path.abspath(path) 返回path規(guī)范化的絕對(duì)路徑 os.path.split(path) 將path分割成目錄和文件名二元組返回 os.path.dirname(path) 返回path的目錄。其實(shí)就是os.path.split(path)的第一個(gè)元素 os.path.basename(path) 返回path最后的文件名。如何path以/或\結(jié)尾,那么就會(huì)返回空值。即os.path.split(path)的第二個(gè)元素 os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False os.path.isabs(path) 如果path是絕對(duì)路徑,返回True os.path.isfile(path) 如果path是一個(gè)存在的文件,返回True。否則返回False os.path.isdir(path) 如果path是一個(gè)存在的目錄,則返回True。否則返回False os.path.join(path1[, path2[, ...]]) 將多個(gè)路徑組合后返回,第一個(gè)絕對(duì)路徑之前的參數(shù)將被忽略 os.path.getatime(path) 返回path所指向的文件或者目錄的最后存取時(shí)間 os.path.getmtime(path) 返回path所指向的文件或者目錄的最后修改時(shí)間
進(jìn)度條代碼
\r 表示當(dāng)前輸出到行首[%-100s] 表示中括號(hào)之間有一百個(gè)站位符,減號(hào)表示從左到右追加字符,加號(hào)從右到左def view_bar(num,total):rate = num / totalrate_num= int(rate * 100)r = '\r[%-100s]%d%%' % ('=' * rate_num, rate_num, )sys.stdout.write(r)sys.stdout.flush()if __name__ == '__main__':for i in range(101):time.sleep(0.1)view_bar(i, 100) 進(jìn)度條代碼
?
hashlib模塊
用于加密相關(guān)的操作,代替了md5模塊和sha模塊,主要提供?SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
import hashlib# ######## md5 ######## hash = hashlib.md5() # help(hash.update) hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest())######## sha1 ########hash = hashlib.sha1() hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest())# ######## sha256 ########hash = hashlib.sha256() hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest())# ######## sha384 ########hash = hashlib.sha384() hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest())# ######## sha512 ########hash = hashlib.sha512() hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest())以上加密算法雖然依然非常厲害,但時(shí)候存在缺陷,即:通過(guò)撞庫(kù)可以反解。所以,有必要對(duì)加密算法中添加自定義key再來(lái)做加密。
import hashlib# ######## md5 ########hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8")) hash.update(bytes('admin',encoding="utf-8")) print(hash.hexdigest())python內(nèi)置還有一個(gè) hmac 模塊,它內(nèi)部對(duì)我們創(chuàng)建 key 和 內(nèi)容 進(jìn)行進(jìn)一步的處理然后再加密
import hmach = hmac.new(bytes('898oaFs09f',encoding="utf-8")) h.update(bytes('admin',encoding="utf-8")) print(h.hexdigest())?
random模塊
取隨機(jī)數(shù),驗(yàn)證碼實(shí)例
import randomprint(random.random()) print(random.randint(1, 2)) print(random.randrange(1, 10))import random checkcode = '' for i in range(4):current = random.randrange(0,4)if current != i:temp = chr(random.randint(65,90))else:temp = random.randint(0,9)checkcode += str(temp) print checkcode 隨機(jī)驗(yàn)證碼
?
re模塊
python中re模塊提供了正則表達(dá)式相關(guān)操作
?
字符:
. 匹配除換行符以外的任意字符\w 匹配字母或數(shù)字或下劃線(xiàn)或漢字\s 匹配任意的空白符\d 匹配數(shù)字\b 匹配單詞的開(kāi)始或結(jié)束^ 匹配字符串的開(kāi)始$ 匹配字符串的結(jié)束次數(shù):
* 重復(fù)零次或更多次+ 重復(fù)一次或更多次? 重復(fù)零次或一次{n} 重復(fù)n次{n,} 重復(fù)n次或更多次{n,m} 重復(fù)n到m次
函數(shù)
match
# match,從起始位置開(kāi)始匹配,匹配成功返回一個(gè)對(duì)象,未匹配成功返回Nonematch(pattern, string, flags=0)# pattern: 正則模型# string : 要匹配的字符串# falgs : 匹配模式 # 無(wú)分組r = re.match("h\w+", origin)print(r.group()) # 獲取匹配到的所有結(jié)果print(r.groups()) # 獲取模型中匹配到的分組結(jié)果print(r.groupdict()) # 獲取模型中匹配到的分組結(jié)果# 有分組# 為何要有分組?提取匹配成功的指定內(nèi)容(先匹配成功全部正則,再匹配成功的局部?jī)?nèi)容提取出來(lái)) r = re.match("h(\w+).*(?P<name>\d)$", origin)print(r.group()) # 獲取匹配到的所有結(jié)果print(r.groups()) # 獲取模型中匹配到的分組結(jié)果print(r.groupdict()) # 獲取模型中匹配到的分組中所有執(zhí)行了key的組 例search
# search,瀏覽整個(gè)字符串去匹配第一個(gè),未匹配成功返回None # search(pattern, string, flags=0) # 無(wú)分組 r = re.search("a\w+", origin)print(r.group()) # 獲取匹配到的所有結(jié)果print(r.groups()) # 獲取模型中匹配到的分組結(jié)果print(r.groupdict()) # 獲取模型中匹配到的分組結(jié)果# 有分組 r = re.search("a(\w+).*(?P<name>\d)$", origin)print(r.group()) # 獲取匹配到的所有結(jié)果print(r.groups()) # 獲取模型中匹配到的分組結(jié)果print(r.groupdict()) # 獲取模型中匹配到的分組中所有執(zhí)行了key的組 例?
findall
# findall,獲取非重復(fù)的匹配列表;如果有一個(gè)組則以列表形式返回,且每一個(gè)匹配均是字符串;如果模型中有多個(gè)組,則以列表形式返回,且每一個(gè)匹配均是元祖; # 空的匹配也會(huì)包含在結(jié)果中 #findall(pattern, string, flags=0) 例sub
# sub,替換匹配成功的指定位置字符串sub(pattern, repl, string, count=0, flags=0) # pattern: 正則模型 # repl : 要替換的字符串或可執(zhí)行對(duì)象 # string : 要匹配的字符串 # count : 指定匹配個(gè)數(shù) # flags : 匹配模式 # 與分組無(wú)關(guān) origin = "hello alex bcd alex lge alex acd 19"r = re.sub("a\w+", "999", origin, 2)print(r) 例split
# split,根據(jù)正則匹配分割字符串split(pattern, string, maxsplit=0, flags=0) # pattern: 正則模型 # string : 要匹配的字符串 # maxsplit:指定分割個(gè)數(shù) # flags : 匹配模式 # 無(wú)分組origin = "hello alex bcd alex lge alex acd 19"r = re.split("alex", origin, 1)print(r)# 有分組 origin = "hello alex bcd alex lge alex acd 19"r1 = re.split("(alex)", origin, 1)print(r1)r2 = re.split("(al(ex))", origin, 1)print(r2) 例?
configparser 模塊
configparser用于處理特定格式的文件,其本質(zhì)上是利用open來(lái)操作文件!
# 注釋1 ; 注釋2[section1] # 節(jié)點(diǎn) k1 = v1 # 值 k2:v2 # 值 [section2] # 節(jié)點(diǎn) k1 = v1 # 值 View Code import configparserconfig = configparser.ConfigParser() # 打開(kāi)一個(gè)configparser對(duì)象 config.read("test", encoding="utf-8") # 將文件傳送給對(duì)象# -------獲取所有節(jié)點(diǎn) ----------# ret = config.sections() print(ret)# -------獲取指定節(jié)點(diǎn)下所有的鍵值對(duì) ----------# ret = config.items('section1') print(ret)# -------獲取制定節(jié)點(diǎn)下的所有件 ----------# ret = config.options('section1') print(ret)# -------獲取指定節(jié)點(diǎn)下的指定key的value ----------# v = config.get('section1', 'k1') #一切皆為str # v = config.getint('section1', 'k1') #數(shù)字可自行轉(zhuǎn)換 # v = config.getfloat('section1', 'k1') #浮點(diǎn)數(shù)自行轉(zhuǎn)換 # v = config.getboolean('section1', 'k1') #布爾值自行轉(zhuǎn)換 print(v)# ---------- 檢查 (返回布爾值)------------ has_sec = config.has_section('section1') print(has_sec)# ---------- 添加節(jié)點(diǎn) ------------ config.add_section("SEC_1") config.write(open('xxxooo', 'w'))# ----------刪除節(jié)點(diǎn)------------ config.remove_section("SEC_1") config.write(open('xxxooo', 'w'))config.add_section("user_msg") # 給config 對(duì)象插入一個(gè)節(jié)點(diǎn),節(jié)點(diǎn)存在會(huì)報(bào)錯(cuò)# -------添加 (section, option, value) ----------# config.set("user_msg", "zshaox", "123") # 給對(duì)象節(jié)點(diǎn)插入件值對(duì)(section, option, value) config.write(open("test", "w")) # 將修改結(jié)果寫(xiě)入原文件# -------刪除 (section, option) ----------# config.remove_option("user_msg", "zshaox") config.write(open("test", "w"))# -------檢查 (section, option) ----------# has_opt = config.has_option("user_msg", "zshaox") print(has_opt)XML 模塊
XML是實(shí)現(xiàn)不同語(yǔ)言或程序之間進(jìn)行數(shù)據(jù)交換的協(xié)議,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>1、解析XML
利用字符串解析成對(duì)象
from xml.etree import ElementTree as ET# 打開(kāi)文件,讀取XML內(nèi)容 str_xml = open('xo.xml', 'r').read()# 將字符串解析成xml特殊對(duì)象,root代指xml文件的根節(jié)點(diǎn) root = ET.XML(str_xml)利用ElementTree.parse將文件直接解析成xml對(duì)象
from xml.etree import ElementTree as ET# 直接解析xml文件 tree = ET.parse("xo.xml")# 獲取xml文件的根節(jié)點(diǎn) root = tree.getroot()2、操作XML
class Element:"""An XML element.This class is the reference implementation of the Element interface.An element's length is its number of subelements. That means if youwant to check if an element is truly empty, you should check BOTHits length AND its text attribute.The element tag, attribute names, and attribute values can be eitherbytes or strings.*tag* is the element name. *attrib* is an optional dictionary containingelement attributes. *extra* are additional element attributes given askeyword arguments.Example form:<tag attrib>text<child/>...</tag>tail"""當(dāng)前節(jié)點(diǎn)的標(biāo)簽名tag = None"""The element's name."""當(dāng)前節(jié)點(diǎn)的屬性attrib = None"""Dictionary of the element's attributes."""當(dāng)前節(jié)點(diǎn)的內(nèi)容text = None"""Text before first subelement. This is either a string or the value None.Note that if there is no text, this attribute may be eitherNone or the empty string, depending on the parser."""tail = None"""Text after this element's end tag, but before the next sibling element'sstart tag. This is either a string or the value None. Note that if therewas no text, this attribute may be either None or an empty string,depending on the parser."""def __init__(self, tag, attrib={}, **extra):if not isinstance(attrib, dict):raise TypeError("attrib must be dict, not %s" % (attrib.__class__.__name__,))attrib = attrib.copy()attrib.update(extra)self.tag = tagself.attrib = attribself._children = []def __repr__(self):return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self))def makeelement(self, tag, attrib):創(chuàng)建一個(gè)新節(jié)點(diǎn)"""Create a new element with the same type.*tag* is a string containing the element name.*attrib* is a dictionary containing the element attributes.Do not call this method, use the SubElement factory function instead."""return self.__class__(tag, attrib)def copy(self):"""Return copy of current element.This creates a shallow copy. Subelements will be shared with theoriginal tree."""elem = self.makeelement(self.tag, self.attrib)elem.text = self.textelem.tail = self.tailelem[:] = selfreturn elemdef __len__(self):return len(self._children)def __bool__(self):warnings.warn("The behavior of this method will change in future versions. ""Use specific 'len(elem)' or 'elem is not None' test instead.",FutureWarning, stacklevel=2)return len(self._children) != 0 # emulate old behaviour, for nowdef __getitem__(self, index):return self._children[index]def __setitem__(self, index, element):# if isinstance(index, slice):# for elt in element:# assert iselement(elt)# else:# assert iselement(element)self._children[index] = elementdef __delitem__(self, index):del self._children[index]def append(self, subelement):為當(dāng)前節(jié)點(diǎn)追加一個(gè)子節(jié)點(diǎn)"""Add *subelement* to the end of this element.The new element will appear in document order after the last existingsubelement (or directly after the text, if it's the first subelement),but before the end tag for this element."""self._assert_is_element(subelement)self._children.append(subelement)def extend(self, elements):為當(dāng)前節(jié)點(diǎn)擴(kuò)展 n 個(gè)子節(jié)點(diǎn)"""Append subelements from a sequence.*elements* is a sequence with zero or more elements."""for element in elements:self._assert_is_element(element)self._children.extend(elements)def insert(self, index, subelement):在當(dāng)前節(jié)點(diǎn)的子節(jié)點(diǎn)中插入某個(gè)節(jié)點(diǎn),即:為當(dāng)前節(jié)點(diǎn)創(chuàng)建子節(jié)點(diǎn),然后插入指定位置"""Insert *subelement* at position *index*."""self._assert_is_element(subelement)self._children.insert(index, subelement)def _assert_is_element(self, e):# Need to refer to the actual Python implementation, not the# shadowing C implementation.if not isinstance(e, _Element_Py):raise TypeError('expected an Element, not %s' % type(e).__name__)def remove(self, subelement):在當(dāng)前節(jié)點(diǎn)在子節(jié)點(diǎn)中刪除某個(gè)節(jié)點(diǎn)"""Remove matching subelement.Unlike the find methods, this method compares elements based onidentity, NOT ON tag value or contents. To remove subelements byother means, the easiest way is to use a list comprehension toselect what elements to keep, and then use slice assignment to updatethe parent element.ValueError is raised if a matching element could not be found."""# assert iselement(element) self._children.remove(subelement)def getchildren(self):獲取所有的子節(jié)點(diǎn)(廢棄)"""(Deprecated) Return all subelements.Elements are returned in document order."""warnings.warn("This method will be removed in future versions. ""Use 'list(elem)' or iteration over elem instead.",DeprecationWarning, stacklevel=2)return self._childrendef find(self, path, namespaces=None):獲取第一個(gè)尋找到的子節(jié)點(diǎn)"""Find first matching element by tag name or path.*path* is a string having either an element tag or an XPath,*namespaces* is an optional mapping from namespace prefix to full name.Return the first matching element, or None if no element was found."""return ElementPath.find(self, path, namespaces)def findtext(self, path, default=None, namespaces=None):獲取第一個(gè)尋找到的子節(jié)點(diǎn)的內(nèi)容"""Find text for first matching element by tag name or path.*path* is a string having either an element tag or an XPath,*default* is the value to return if the element was not found,*namespaces* is an optional mapping from namespace prefix to full name.Return text content of first matching element, or default value ifnone was found. Note that if an element is found having no textcontent, the empty string is returned."""return ElementPath.findtext(self, path, default, namespaces)def findall(self, path, namespaces=None):獲取所有的子節(jié)點(diǎn)"""Find all matching subelements by tag name or path.*path* is a string having either an element tag or an XPath,*namespaces* is an optional mapping from namespace prefix to full name.Returns list containing all matching elements in document order."""return ElementPath.findall(self, path, namespaces)def iterfind(self, path, namespaces=None):獲取所有指定的節(jié)點(diǎn),并創(chuàng)建一個(gè)迭代器(可以被for循環(huán))"""Find all matching subelements by tag name or path.*path* is a string having either an element tag or an XPath,*namespaces* is an optional mapping from namespace prefix to full name.Return an iterable yielding all matching elements in document order."""return ElementPath.iterfind(self, path, namespaces)def clear(self):清空節(jié)點(diǎn)"""Reset element.This function removes all subelements, clears all attributes, and setsthe text and tail attributes to None."""self.attrib.clear()self._children = []self.text = self.tail = Nonedef get(self, key, default=None):獲取當(dāng)前節(jié)點(diǎn)的屬性值"""Get element attribute.Equivalent to attrib.get, but some implementations may handle this abit more efficiently. *key* is what attribute to look for, and*default* is what to return if the attribute was not found.Returns a string containing the attribute value, or the default ifattribute was not found."""return self.attrib.get(key, default)def set(self, key, value):為當(dāng)前節(jié)點(diǎn)設(shè)置屬性值"""Set element attribute.Equivalent to attrib[key] = value, but some implementations may handlethis a bit more efficiently. *key* is what attribute to set, and*value* is the attribute value to set it to."""self.attrib[key] = valuedef keys(self):獲取當(dāng)前節(jié)點(diǎn)的所有屬性的 key"""Get list of attribute names.Names are returned in an arbitrary order, just like an ordinaryPython dict. Equivalent to attrib.keys()"""return self.attrib.keys()def items(self):獲取當(dāng)前節(jié)點(diǎn)的所有屬性值,每個(gè)屬性都是一個(gè)鍵值對(duì)"""Get element attributes as a sequence.The attributes are returned in arbitrary order. Equivalent toattrib.items().Return a list of (name, value) tuples."""return self.attrib.items()def iter(self, tag=None):在當(dāng)前節(jié)點(diǎn)的子孫中根據(jù)節(jié)點(diǎn)名稱(chēng)尋找所有指定的節(jié)點(diǎn),并返回一個(gè)迭代器(可以被for循環(huán))。"""Create tree iterator.The iterator loops over the element and all subelements in documentorder, returning all elements with a matching tag.If the tree structure is modified during iteration, new or removedelements may or may not be included. To get a stable set, use thelist() function on the iterator, and loop over the resulting list.*tag* is what tags to look for (default is to return all elements)Return an iterator containing all the matching elements."""if tag == "*":tag = Noneif tag is None or self.tag == tag:yield selffor e in self._children:yield from e.iter(tag)# compatibilitydef getiterator(self, tag=None):# Change for a DeprecationWarning in 1.4 warnings.warn("This method will be removed in future versions. ""Use 'elem.iter()' or 'list(elem.iter())' instead.",PendingDeprecationWarning, stacklevel=2)return list(self.iter(tag))def itertext(self):在當(dāng)前節(jié)點(diǎn)的子孫中根據(jù)節(jié)點(diǎn)名稱(chēng)尋找所有指定的節(jié)點(diǎn)的內(nèi)容,并返回一個(gè)迭代器(可以被for循環(huán))。"""Create text iterator.The iterator loops over the element and all subelements in documentorder, returning all inner text."""tag = self.tagif not isinstance(tag, str) and tag is not None:returnif self.text:yield self.textfor e in self:yield from e.itertext()if e.tail:yield e.tail節(jié)點(diǎn)功能一覽表 節(jié)點(diǎn)操作方法1)遍歷XML文檔的所有內(nèi)容
from xml.etree import ElementTree as ET############ 解析方式一 ############ """ # 打開(kāi)文件,讀取XML內(nèi)容 str_xml = open('xo.xml', 'r').read()# 將字符串解析成xml特殊對(duì)象,root代指xml文件的根節(jié)點(diǎn) root = ET.XML(str_xml) """ ############ 解析方式二 ############# 直接解析xml文件 tree = ET.parse("xo.xml")# 獲取xml文件的根節(jié)點(diǎn) root = tree.getroot()### 操作# 頂層標(biāo)簽 print(root.tag)# 遍歷XML文檔的第二層 for child in root:# 第二層節(jié)點(diǎn)的標(biāo)簽名稱(chēng)和標(biāo)簽屬性print(child.tag, child.attrib)# 遍歷XML文檔的第三層for i in child:# 第二層節(jié)點(diǎn)的標(biāo)簽名稱(chēng)和內(nèi)容print(i.tag,i.text) View Code2)遍歷XML中指定的節(jié)點(diǎn)
from xml.etree import ElementTree as ET############ 解析方式一 ############ """ # 打開(kāi)文件,讀取XML內(nèi)容 str_xml = open('xo.xml', 'r').read()# 將字符串解析成xml特殊對(duì)象,root代指xml文件的根節(jié)點(diǎn) root = ET.XML(str_xml) """ ############ 解析方式二 ############# 直接解析xml文件 tree = ET.parse("xo.xml")# 獲取xml文件的根節(jié)點(diǎn) root = tree.getroot()### 操作# 頂層標(biāo)簽 print(root.tag)# 遍歷XML中所有的year節(jié)點(diǎn) for node in root.iter('year'):# 節(jié)點(diǎn)的標(biāo)簽名稱(chēng)和內(nèi)容print(node.tag, node.text) View Code?
3)修改節(jié)點(diǎn)內(nèi)容
由于修改的節(jié)點(diǎn)時(shí),均是在內(nèi)存中進(jìn)行,其不會(huì)影響文件中的內(nèi)容。所以,如果想要修改,則需要重新將內(nèi)存中的內(nèi)容寫(xiě)到文件
from xml.etree import ElementTree as ET############ 解析方式一 ############# 打開(kāi)文件,讀取XML內(nèi)容 str_xml = open('xo.xml', 'r').read()# 將字符串解析成xml特殊對(duì)象,root代指xml文件的根節(jié)點(diǎn) root = ET.XML(str_xml)############ 操作 ############# 頂層標(biāo)簽 print(root.tag)# 循環(huán)所有的year節(jié)點(diǎn) for node in root.iter('year'):# 將year節(jié)點(diǎn)中的內(nèi)容自增一new_year = int(node.text) + 1node.text = str(new_year)# 設(shè)置屬性node.set('name', 'alex')node.set('age', '18')# 刪除屬性del node.attrib['name']############ 保存文件 ############ tree = ET.ElementTree(root) tree.write("newnew.xml", encoding='utf-8') 解析字符串方式,修改,保存 from xml.etree import ElementTree as ET############ 解析方式二 ############# 直接解析xml文件 tree = ET.parse("xo.xml")# 獲取xml文件的根節(jié)點(diǎn) root = tree.getroot()############ 操作 ############# 頂層標(biāo)簽 print(root.tag)# 循環(huán)所有的year節(jié)點(diǎn) for node in root.iter('year'):# 將year節(jié)點(diǎn)中的內(nèi)容自增一new_year = int(node.text) + 1node.text = str(new_year)# 設(shè)置屬性node.set('name', 'alex')node.set('age', '18')# 刪除屬性del node.attrib['name']############ 保存文件 ############ tree.write("newnew.xml", encoding='utf-8') 解析文件方式,修改,保存4)刪除節(jié)點(diǎn)
from xml.etree import ElementTree as ET############ 解析字符串方式打開(kāi) ############# 打開(kāi)文件,讀取XML內(nèi)容 str_xml = open('xo.xml', 'r').read()# 將字符串解析成xml特殊對(duì)象,root代指xml文件的根節(jié)點(diǎn) root = ET.XML(str_xml)############ 操作 ############# 頂層標(biāo)簽 print(root.tag)# 遍歷data下的所有country節(jié)點(diǎn) for country in root.findall('country'):# 獲取每一個(gè)country節(jié)點(diǎn)下rank節(jié)點(diǎn)的內(nèi)容rank = int(country.find('rank').text)if rank > 50:# 刪除指定country節(jié)點(diǎn) root.remove(country)############ 保存文件 ############ tree = ET.ElementTree(root) tree.write("newnew.xml", encoding='utf-8') 解析字符串方式打開(kāi),刪除,保存 from xml.etree import ElementTree as ET############ 解析文件方式 ############# 直接解析xml文件 tree = ET.parse("xo.xml")# 獲取xml文件的根節(jié)點(diǎn) root = tree.getroot()############ 操作 ############# 頂層標(biāo)簽 print(root.tag)# 遍歷data下的所有country節(jié)點(diǎn) for country in root.findall('country'):# 獲取每一個(gè)country節(jié)點(diǎn)下rank節(jié)點(diǎn)的內(nèi)容rank = int(country.find('rank').text)if rank > 50:# 刪除指定country節(jié)點(diǎn) root.remove(country)############ 保存文件 ############ tree.write("newnew.xml", encoding='utf-8') 解析文件方式打開(kāi),刪除,保存3、創(chuàng)建XML文檔
from xml.etree import ElementTree as ET# 創(chuàng)建根節(jié)點(diǎn) root = ET.Element("famliy")# 創(chuàng)建節(jié)點(diǎn)大兒子 son1 = ET.Element('son', {'name': '兒1'}) # 創(chuàng)建小兒子 son2 = ET.Element('son', {"name": '兒2'})# 在大兒子中創(chuàng)建兩個(gè)孫子 grandson1 = ET.Element('grandson', {'name': '兒11'}) grandson2 = ET.Element('grandson', {'name': '兒12'}) son1.append(grandson1) son1.append(grandson2)# 把兒子添加到根節(jié)點(diǎn)中 root.append(son1) root.append(son1)tree = ET.ElementTree(root) tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False) 創(chuàng)建方式一 from xml.etree import ElementTree as ET# 創(chuàng)建根節(jié)點(diǎn) root = ET.Element("famliy")# 創(chuàng)建大兒子 # son1 = ET.Element('son', {'name': '兒1'}) son1 = root.makeelement('son', {'name': '兒1'}) # 創(chuàng)建小兒子 # son2 = ET.Element('son', {"name": '兒2'}) son2 = root.makeelement('son', {"name": '兒2'})# 在大兒子中創(chuàng)建兩個(gè)孫子 # grandson1 = ET.Element('grandson', {'name': '兒11'}) grandson1 = son1.makeelement('grandson', {'name': '兒11'}) # grandson2 = ET.Element('grandson', {'name': '兒12'}) grandson2 = son1.makeelement('grandson', {'name': '兒12'})son1.append(grandson1) son1.append(grandson2)# 把兒子添加到根節(jié)點(diǎn)中 root.append(son1) root.append(son1)tree = ET.ElementTree(root) tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False) 創(chuàng)建方式二 from xml.etree import ElementTree as ET# 創(chuàng)建根節(jié)點(diǎn) root = ET.Element("famliy")# 創(chuàng)建節(jié)點(diǎn)大兒子 son1 = ET.SubElement(root, "son", attrib={'name': '兒1'}) # 創(chuàng)建小兒子 son2 = ET.SubElement(root, "son", attrib={"name": "兒2"})# 在大兒子中創(chuàng)建一個(gè)孫子 grandson1 = ET.SubElement(son1, "age", attrib={'name': '兒11'}) grandson1.text = '孫子'et = ET.ElementTree(root) #生成文檔對(duì)象 et.write("test.xml", encoding="utf-8", xml_declaration=True, short_empty_elements=False) 創(chuàng)建方式三由于原生保存的XML時(shí)默認(rèn)無(wú)縮進(jìn),如果想要設(shè)置縮進(jìn)的話(huà), 需要修改保存方式:
from xml.etree import ElementTree as ET from xml.dom import minidomdef prettify(elem):"""將節(jié)點(diǎn)轉(zhuǎn)換成字符串,并添加縮進(jìn)。"""rough_string = ET.tostring(elem, 'utf-8')reparsed = minidom.parseString(rough_string)return reparsed.toprettyxml(indent="\t")# 創(chuàng)建根節(jié)點(diǎn) root = ET.Element("famliy")# 創(chuàng)建大兒子 # son1 = ET.Element('son', {'name': '兒1'}) son1 = root.makeelement('son', {'name': '兒1'}) # 創(chuàng)建小兒子 # son2 = ET.Element('son', {"name": '兒2'}) son2 = root.makeelement('son', {"name": '兒2'})# 在大兒子中創(chuàng)建兩個(gè)孫子 # grandson1 = ET.Element('grandson', {'name': '兒11'}) grandson1 = son1.makeelement('grandson', {'name': '兒11'}) # grandson2 = ET.Element('grandson', {'name': '兒12'}) grandson2 = son1.makeelement('grandson', {'name': '兒12'})son1.append(grandson1) son1.append(grandson2)# 把兒子添加到根節(jié)點(diǎn)中 root.append(son1) root.append(son1)raw_str = prettify(root)f = open("xxxoo.xml",'w',encoding='utf-8') f.write(raw_str) f.close() 縮進(jìn)形式保存?
shutil 模塊
高級(jí)的 文件、文件夾、壓縮包 處理模塊
將文件內(nèi)容拷貝到另一個(gè)文件中
import shutilshutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))拷貝文件
shutil.copyfile('f1.log', 'f2.log')僅拷貝權(quán)限。內(nèi)容、組、用戶(hù)均不變
shutil.copymode('f1.log', 'f2.log')僅拷貝狀態(tài)的信息,包括:mode bits, atime, mtime, flags
shutil.copystat('f1.log', 'f2.log')拷貝文件和權(quán)限
shutil.copy('f1.log', 'f2.log')拷貝文件和狀態(tài)信息
shutil.copy2('f1.log', 'f2.log')遞歸的去拷貝文件夾
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))遞歸的去刪除文件
shutil.rmtree('folder1')遞歸的去移動(dòng)文件,它類(lèi)似mv命令,其實(shí)就是重命名。
shutil.move('folder1', 'folder3')?
zipfile 壓縮
import zipfile# 壓縮 z = zipfile.ZipFile('laxi.zip', 'w') z.write('a.log') z.write('data.data') z.close()# 解壓 z = zipfile.ZipFile('laxi.zip', 'r') z.extractall() z.close()
tarfile 壓縮
import tarfile# 壓縮 tar = tarfile.open('your.tar','w') tar.add('/Users/wupeiqi/PycharmProjects/bbs2.log', arcname='bbs2.log') tar.add('/Users/wupeiqi/PycharmProjects/cmdb.log', arcname='cmdb.log') tar.close()# 解壓 tar = tarfile.open('your.tar','r') tar.extractall() # 可設(shè)置解壓地址 tar.close()系統(tǒng)命令模塊
1、可以執(zhí)行shell命令的相關(guān)模塊和函數(shù)有:
- os.system
- os.spawn*
- os.popen* ? ? ? ? ?--廢棄
- popen2.* ? ? ? ? ? --廢棄
- commands.* ? ? ?--廢棄,3.x中被移除
以上執(zhí)行shell命令的相關(guān)的模塊和函數(shù)的功能均在 subprocess 模塊中實(shí)現(xiàn),并提供了更豐富的功能。
call?
執(zhí)行命令,返回狀態(tài)碼
ret = subprocess.call(["ls", "-l"], shell=False) ret = subprocess.call("ls -l", shell=True)check_call
執(zhí)行命令,如果執(zhí)行狀態(tài)碼是 0 ,則返回0,否則拋異常
subprocess.check_call(["ls", "-l"]) subprocess.check_call("exit 1", shell=True)check_output
執(zhí)行命令,如果狀態(tài)碼是 0 ,則返回執(zhí)行結(jié)果,否則拋異常
subprocess.check_output(["echo", "Hello World!"]) subprocess.check_output("exit 1", shell=True)subprocess.Popen(...)
args:shell命令,可以是字符串或者序列類(lèi)型(如:list,元組) bufsize:指定緩沖。0 無(wú)緩沖,1 行緩沖,其他 緩沖區(qū)大小,負(fù)值 系統(tǒng)緩沖 stdin, stdout, stderr:分別表示程序的標(biāo)準(zhǔn)輸入、輸出、錯(cuò)誤句柄 preexec_fn:只在Unix平臺(tái)下有效,用于指定一個(gè)可執(zhí)行對(duì)象(callable object),它將在子進(jìn)程運(yùn)行之前被調(diào)用 close_sfs:在windows平臺(tái)下,如果close_fds被設(shè)置為T(mén)rue,則新創(chuàng)建的子進(jìn)程將不會(huì)繼承父進(jìn)程的輸入、輸出、錯(cuò)誤管道。 所以不能將close_fds設(shè)置為T(mén)rue同時(shí)重定向子進(jìn)程的標(biāo)準(zhǔn)輸入、輸出與錯(cuò)誤(stdin, stdout, stderr)。 shell:同上 cwd:用于設(shè)置子進(jìn)程的當(dāng)前目錄 env:用于指定子進(jìn)程的環(huán)境變量。如果env = None,子進(jìn)程的環(huán)境變量將從父進(jìn)程中繼承。 universal_newlines:不同系統(tǒng)的換行符不同,True -> 同意使用 \n startupinfo與createionflags只在windows下有效 將被傳遞給底層的CreateProcess()函數(shù),用于設(shè)置子進(jìn)程的一些屬性,如:主窗口的外觀,進(jìn)程的優(yōu)先級(jí)等等import subprocessobj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',) cwd 指定之行所在目錄 import subprocessobj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) obj.stdin.write("print(1)\n") obj.stdin.write("print(2)")out_error_list = obj.communicate() print(out_error_list) 多命令執(zhí)行獲取輸出以及錯(cuò)誤 import subprocessobj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) out_error_list = obj.communicate('print("hello")') print(out_error_list) 單條命了執(zhí)行獲取輸出以及錯(cuò)誤
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/zshaox/p/5598284.html
總結(jié)
以上是生活随笔為你收集整理的python 学习 [day6]的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: (王道408考研数据结构)第五章树-第三
- 下一篇: Python Numpy 数组的初始化和