python 学习 [day6]
遞歸階乘:
函數自己調用自己循環操作的模式稱之為遞歸
def func(num):if num == 1:return 1return num * func(num - 1)print(func(7)) 遞歸階乘反射:
含義:通過字符串的形式去對象(模塊)中操作(尋找/檢查/刪除/設置)成員
通過字符串形式調用模塊方法 使用getattr()
通過字符串形式調用模塊 采用__import__("inp", fromlist=Ture) ?fromlist參數傳輸什么路徑就倒入什么路徑,如果沒有該參數,將無法導入inp.account類型
hasattr(對象, 字符串) 檢查對象中是否存在匹配字符串的方法,存在 返回True 不存在返回Falsefunc = getattr(對象, 字符串) 將對象中匹配字符串的函數體賦值給func對象,在通過func()執行函數setattr(對象, 字符串, 值) 在對象中插入函數delattr(對象, 字符串) 刪除對象中字符串匹配的函數體 #run函數 根據用戶輸入(commands/login),完成倒入commands模塊并執行login方法; def run():inp = input("請輸入要訪問的url")m, f = inp.split("/")if hasattr(m, f):func = getattr(m, f)func()else:print('404') 字符串調用函數?
模塊中的特殊變量
__name__ #當執行當前文件時當前文件的特殊變量__name__ == '__main__',否則__name__不等于__main____file__ #獲取當前之行腳本的相對路徑os.path.abspath(__file__) #獲取文件的絕對路徑os.path.dirname("dir/file") #文件或目錄的上級目錄sys模塊
sys.argv 命令行參數List,第一個元素是程序本身路徑 sys.exit(n) 退出程序,正常退出時exit(0) sys.version 獲取Python解釋程序的版本信息 sys.maxint 最大的Int值 sys.path 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值 sys.platform 返回操作系統平臺名稱 sys.stdin 輸入相關 sys.stdout 輸出相關 sys.stderror 錯誤相關os模塊
os.getcwd() 獲取當前工作目錄,即當前python腳本工作的目錄路徑 os.chdir("dirname") 改變當前腳本工作目錄;相當于shell下cd os.curdir 返回當前目錄: ('.') os.pardir 獲取當前目錄的父目錄字符串名:('..') os.makedirs('dir1/dir2') 可生成多層遞歸目錄 os.removedirs('dirname1') 若目錄為空,則刪除,并遞歸到上一級目錄,如若也為空,則刪除,依此類推 os.mkdir('dirname') 生成單級目錄;相當于shell中mkdir dirname os.rmdir('dirname') 刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當于shell中rmdir dirname os.listdir('dirname') 列出指定目錄下的所有文件和子目錄,包括隱藏文件,并以列表方式打印 os.remove() 刪除一個文件 os.rename("oldname","new") 重命名文件/目錄 os.stat('path/filename') 獲取文件/目錄信息 os.sep 操作系統特定的路徑分隔符,win下為"\\",Linux下為"/" os.linesep 當前平臺使用的行終止符,win下為"\t\n",Linux下為"\n" os.pathsep 用于分割文件路徑的字符串 os.name 字符串指示當前使用平臺。win->'nt'; Linux->'posix' os.system("bash command") 運行shell命令,直接顯示 os.environ 獲取系統環境變量 os.path.abspath(path) 返回path規范化的絕對路徑 os.path.split(path) 將path分割成目錄和文件名二元組返回 os.path.dirname(path) 返回path的目錄。其實就是os.path.split(path)的第一個元素 os.path.basename(path) 返回path最后的文件名。如何path以/或\結尾,那么就會返回空值。即os.path.split(path)的第二個元素 os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False os.path.isabs(path) 如果path是絕對路徑,返回True os.path.isfile(path) 如果path是一個存在的文件,返回True。否則返回False os.path.isdir(path) 如果path是一個存在的目錄,則返回True。否則返回False os.path.join(path1[, path2[, ...]]) 將多個路徑組合后返回,第一個絕對路徑之前的參數將被忽略 os.path.getatime(path) 返回path所指向的文件或者目錄的最后存取時間 os.path.getmtime(path) 返回path所指向的文件或者目錄的最后修改時間
進度條代碼
\r 表示當前輸出到行首[%-100s] 表示中括號之間有一百個站位符,減號表示從左到右追加字符,加號從右到左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) 進度條代碼
?
hashlib模塊
用于加密相關的操作,代替了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())以上加密算法雖然依然非常厲害,但時候存在缺陷,即:通過撞庫可以反解。所以,有必要對加密算法中添加自定義key再來做加密。
import hashlib# ######## md5 ########hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8")) hash.update(bytes('admin',encoding="utf-8")) print(hash.hexdigest())python內置還有一個 hmac 模塊,它內部對我們創建 key 和 內容 進行進一步的處理然后再加密
import hmach = hmac.new(bytes('898oaFs09f',encoding="utf-8")) h.update(bytes('admin',encoding="utf-8")) print(h.hexdigest())?
random模塊
取隨機數,驗證碼實例
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 隨機驗證碼
?
re模塊
python中re模塊提供了正則表達式相關操作
?
字符:
. 匹配除換行符以外的任意字符\w 匹配字母或數字或下劃線或漢字\s 匹配任意的空白符\d 匹配數字\b 匹配單詞的開始或結束^ 匹配字符串的開始$ 匹配字符串的結束次數:
* 重復零次或更多次+ 重復一次或更多次? 重復零次或一次{n} 重復n次{n,} 重復n次或更多次{n,m} 重復n到m次
函數
match
# match,從起始位置開始匹配,匹配成功返回一個對象,未匹配成功返回Nonematch(pattern, string, flags=0)# pattern: 正則模型# string : 要匹配的字符串# falgs : 匹配模式 # 無分組r = re.match("h\w+", origin)print(r.group()) # 獲取匹配到的所有結果print(r.groups()) # 獲取模型中匹配到的分組結果print(r.groupdict()) # 獲取模型中匹配到的分組結果# 有分組# 為何要有分組?提取匹配成功的指定內容(先匹配成功全部正則,再匹配成功的局部內容提取出來) r = re.match("h(\w+).*(?P<name>\d)$", origin)print(r.group()) # 獲取匹配到的所有結果print(r.groups()) # 獲取模型中匹配到的分組結果print(r.groupdict()) # 獲取模型中匹配到的分組中所有執行了key的組 例search
# search,瀏覽整個字符串去匹配第一個,未匹配成功返回None # search(pattern, string, flags=0) # 無分組 r = re.search("a\w+", origin)print(r.group()) # 獲取匹配到的所有結果print(r.groups()) # 獲取模型中匹配到的分組結果print(r.groupdict()) # 獲取模型中匹配到的分組結果# 有分組 r = re.search("a(\w+).*(?P<name>\d)$", origin)print(r.group()) # 獲取匹配到的所有結果print(r.groups()) # 獲取模型中匹配到的分組結果print(r.groupdict()) # 獲取模型中匹配到的分組中所有執行了key的組 例?
findall
# findall,獲取非重復的匹配列表;如果有一個組則以列表形式返回,且每一個匹配均是字符串;如果模型中有多個組,則以列表形式返回,且每一個匹配均是元祖; # 空的匹配也會包含在結果中 #findall(pattern, string, flags=0) 例sub
# sub,替換匹配成功的指定位置字符串sub(pattern, repl, string, count=0, flags=0) # pattern: 正則模型 # repl : 要替換的字符串或可執行對象 # string : 要匹配的字符串 # count : 指定匹配個數 # flags : 匹配模式 # 與分組無關 origin = "hello alex bcd alex lge alex acd 19"r = re.sub("a\w+", "999", origin, 2)print(r) 例split
# split,根據正則匹配分割字符串split(pattern, string, maxsplit=0, flags=0) # pattern: 正則模型 # string : 要匹配的字符串 # maxsplit:指定分割個數 # flags : 匹配模式 # 無分組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用于處理特定格式的文件,其本質上是利用open來操作文件!
# 注釋1 ; 注釋2[section1] # 節點 k1 = v1 # 值 k2:v2 # 值 [section2] # 節點 k1 = v1 # 值 View Code import configparserconfig = configparser.ConfigParser() # 打開一個configparser對象 config.read("test", encoding="utf-8") # 將文件傳送給對象# -------獲取所有節點 ----------# ret = config.sections() print(ret)# -------獲取指定節點下所有的鍵值對 ----------# ret = config.items('section1') print(ret)# -------獲取制定節點下的所有件 ----------# ret = config.options('section1') print(ret)# -------獲取指定節點下的指定key的value ----------# v = config.get('section1', 'k1') #一切皆為str # v = config.getint('section1', 'k1') #數字可自行轉換 # v = config.getfloat('section1', 'k1') #浮點數自行轉換 # v = config.getboolean('section1', 'k1') #布爾值自行轉換 print(v)# ---------- 檢查 (返回布爾值)------------ has_sec = config.has_section('section1') print(has_sec)# ---------- 添加節點 ------------ config.add_section("SEC_1") config.write(open('xxxooo', 'w'))# ----------刪除節點------------ config.remove_section("SEC_1") config.write(open('xxxooo', 'w'))config.add_section("user_msg") # 給config 對象插入一個節點,節點存在會報錯# -------添加 (section, option, value) ----------# config.set("user_msg", "zshaox", "123") # 給對象節點插入件值對(section, option, value) config.write(open("test", "w")) # 將修改結果寫入原文件# -------刪除 (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是實現不同語言或程序之間進行數據交換的協議,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
利用字符串解析成對象
from xml.etree import ElementTree as ET# 打開文件,讀取XML內容 str_xml = open('xo.xml', 'r').read()# 將字符串解析成xml特殊對象,root代指xml文件的根節點 root = ET.XML(str_xml)利用ElementTree.parse將文件直接解析成xml對象
from xml.etree import ElementTree as ET# 直接解析xml文件 tree = ET.parse("xo.xml")# 獲取xml文件的根節點 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"""當前節點的標簽名tag = None"""The element's name."""當前節點的屬性attrib = None"""Dictionary of the element's attributes."""當前節點的內容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):創建一個新節點"""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):為當前節點追加一個子節點"""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):為當前節點擴展 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):在當前節點的子節點中插入某個節點,即:為當前節點創建子節點,然后插入指定位置"""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):在當前節點在子節點中刪除某個節點"""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):獲取所有的子節點(廢棄)"""(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):獲取第一個尋找到的子節點"""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):獲取第一個尋找到的子節點的內容"""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):獲取所有的子節點"""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):獲取所有指定的節點,并創建一個迭代器(可以被for循環)"""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):清空節點"""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):獲取當前節點的屬性值"""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):為當前節點設置屬性值"""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):獲取當前節點的所有屬性的 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):獲取當前節點的所有屬性值,每個屬性都是一個鍵值對"""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):在當前節點的子孫中根據節點名稱尋找所有指定的節點,并返回一個迭代器(可以被for循環)。"""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):在當前節點的子孫中根據節點名稱尋找所有指定的節點的內容,并返回一個迭代器(可以被for循環)。"""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節點功能一覽表 節點操作方法1)遍歷XML文檔的所有內容
from xml.etree import ElementTree as ET############ 解析方式一 ############ """ # 打開文件,讀取XML內容 str_xml = open('xo.xml', 'r').read()# 將字符串解析成xml特殊對象,root代指xml文件的根節點 root = ET.XML(str_xml) """ ############ 解析方式二 ############# 直接解析xml文件 tree = ET.parse("xo.xml")# 獲取xml文件的根節點 root = tree.getroot()### 操作# 頂層標簽 print(root.tag)# 遍歷XML文檔的第二層 for child in root:# 第二層節點的標簽名稱和標簽屬性print(child.tag, child.attrib)# 遍歷XML文檔的第三層for i in child:# 第二層節點的標簽名稱和內容print(i.tag,i.text) View Code2)遍歷XML中指定的節點
from xml.etree import ElementTree as ET############ 解析方式一 ############ """ # 打開文件,讀取XML內容 str_xml = open('xo.xml', 'r').read()# 將字符串解析成xml特殊對象,root代指xml文件的根節點 root = ET.XML(str_xml) """ ############ 解析方式二 ############# 直接解析xml文件 tree = ET.parse("xo.xml")# 獲取xml文件的根節點 root = tree.getroot()### 操作# 頂層標簽 print(root.tag)# 遍歷XML中所有的year節點 for node in root.iter('year'):# 節點的標簽名稱和內容print(node.tag, node.text) View Code?
3)修改節點內容
由于修改的節點時,均是在內存中進行,其不會影響文件中的內容。所以,如果想要修改,則需要重新將內存中的內容寫到文件
from xml.etree import ElementTree as ET############ 解析方式一 ############# 打開文件,讀取XML內容 str_xml = open('xo.xml', 'r').read()# 將字符串解析成xml特殊對象,root代指xml文件的根節點 root = ET.XML(str_xml)############ 操作 ############# 頂層標簽 print(root.tag)# 循環所有的year節點 for node in root.iter('year'):# 將year節點中的內容自增一new_year = int(node.text) + 1node.text = str(new_year)# 設置屬性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文件的根節點 root = tree.getroot()############ 操作 ############# 頂層標簽 print(root.tag)# 循環所有的year節點 for node in root.iter('year'):# 將year節點中的內容自增一new_year = int(node.text) + 1node.text = str(new_year)# 設置屬性node.set('name', 'alex')node.set('age', '18')# 刪除屬性del node.attrib['name']############ 保存文件 ############ tree.write("newnew.xml", encoding='utf-8') 解析文件方式,修改,保存4)刪除節點
from xml.etree import ElementTree as ET############ 解析字符串方式打開 ############# 打開文件,讀取XML內容 str_xml = open('xo.xml', 'r').read()# 將字符串解析成xml特殊對象,root代指xml文件的根節點 root = ET.XML(str_xml)############ 操作 ############# 頂層標簽 print(root.tag)# 遍歷data下的所有country節點 for country in root.findall('country'):# 獲取每一個country節點下rank節點的內容rank = int(country.find('rank').text)if rank > 50:# 刪除指定country節點 root.remove(country)############ 保存文件 ############ 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文件的根節點 root = tree.getroot()############ 操作 ############# 頂層標簽 print(root.tag)# 遍歷data下的所有country節點 for country in root.findall('country'):# 獲取每一個country節點下rank節點的內容rank = int(country.find('rank').text)if rank > 50:# 刪除指定country節點 root.remove(country)############ 保存文件 ############ tree.write("newnew.xml", encoding='utf-8') 解析文件方式打開,刪除,保存3、創建XML文檔
from xml.etree import ElementTree as ET# 創建根節點 root = ET.Element("famliy")# 創建節點大兒子 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(son1)tree = ET.ElementTree(root) tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False) 創建方式一 from xml.etree import ElementTree as ET# 創建根節點 root = ET.Element("famliy")# 創建大兒子 # son1 = ET.Element('son', {'name': '兒1'}) son1 = root.makeelement('son', {'name': '兒1'}) # 創建小兒子 # son2 = ET.Element('son', {"name": '兒2'}) son2 = root.makeelement('son', {"name": '兒2'})# 在大兒子中創建兩個孫子 # 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)# 把兒子添加到根節點中 root.append(son1) root.append(son1)tree = ET.ElementTree(root) tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False) 創建方式二 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", xml_declaration=True, short_empty_elements=False) 創建方式三由于原生保存的XML時默認無縮進,如果想要設置縮進的話, 需要修改保存方式:
from xml.etree import ElementTree as ET from xml.dom import minidomdef prettify(elem):"""將節點轉換成字符串,并添加縮進。"""rough_string = ET.tostring(elem, 'utf-8')reparsed = minidom.parseString(rough_string)return reparsed.toprettyxml(indent="\t")# 創建根節點 root = ET.Element("famliy")# 創建大兒子 # son1 = ET.Element('son', {'name': '兒1'}) son1 = root.makeelement('son', {'name': '兒1'}) # 創建小兒子 # son2 = ET.Element('son', {"name": '兒2'}) son2 = root.makeelement('son', {"name": '兒2'})# 在大兒子中創建兩個孫子 # 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)# 把兒子添加到根節點中 root.append(son1) root.append(son1)raw_str = prettify(root)f = open("xxxoo.xml",'w',encoding='utf-8') f.write(raw_str) f.close() 縮進形式保存?
shutil 模塊
高級的 文件、文件夾、壓縮包 處理模塊
將文件內容拷貝到另一個文件中
import shutilshutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))拷貝文件
shutil.copyfile('f1.log', 'f2.log')僅拷貝權限。內容、組、用戶均不變
shutil.copymode('f1.log', 'f2.log')僅拷貝狀態的信息,包括:mode bits, atime, mtime, flags
shutil.copystat('f1.log', 'f2.log')拷貝文件和權限
shutil.copy('f1.log', 'f2.log')拷貝文件和狀態信息
shutil.copy2('f1.log', 'f2.log')遞歸的去拷貝文件夾
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))遞歸的去刪除文件
shutil.rmtree('folder1')遞歸的去移動文件,它類似mv命令,其實就是重命名。
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() # 可設置解壓地址 tar.close()系統命令模塊
1、可以執行shell命令的相關模塊和函數有:
- os.system
- os.spawn*
- os.popen* ? ? ? ? ?--廢棄
- popen2.* ? ? ? ? ? --廢棄
- commands.* ? ? ?--廢棄,3.x中被移除
以上執行shell命令的相關的模塊和函數的功能均在 subprocess 模塊中實現,并提供了更豐富的功能。
call?
執行命令,返回狀態碼
ret = subprocess.call(["ls", "-l"], shell=False) ret = subprocess.call("ls -l", shell=True)check_call
執行命令,如果執行狀態碼是 0 ,則返回0,否則拋異常
subprocess.check_call(["ls", "-l"]) subprocess.check_call("exit 1", shell=True)check_output
執行命令,如果狀態碼是 0 ,則返回執行結果,否則拋異常
subprocess.check_output(["echo", "Hello World!"]) subprocess.check_output("exit 1", shell=True)subprocess.Popen(...)
args:shell命令,可以是字符串或者序列類型(如:list,元組) bufsize:指定緩沖。0 無緩沖,1 行緩沖,其他 緩沖區大小,負值 系統緩沖 stdin, stdout, stderr:分別表示程序的標準輸入、輸出、錯誤句柄 preexec_fn:只在Unix平臺下有效,用于指定一個可執行對象(callable object),它將在子進程運行之前被調用 close_sfs:在windows平臺下,如果close_fds被設置為True,則新創建的子進程將不會繼承父進程的輸入、輸出、錯誤管道。 所以不能將close_fds設置為True同時重定向子進程的標準輸入、輸出與錯誤(stdin, stdout, stderr)。 shell:同上 cwd:用于設置子進程的當前目錄 env:用于指定子進程的環境變量。如果env = None,子進程的環境變量將從父進程中繼承。 universal_newlines:不同系統的換行符不同,True -> 同意使用 \n startupinfo與createionflags只在windows下有效 將被傳遞給底層的CreateProcess()函數,用于設置子進程的一些屬性,如:主窗口的外觀,進程的優先級等等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) 多命令執行獲取輸出以及錯誤 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) 單條命了執行獲取輸出以及錯誤
?
?
?
轉載于:https://www.cnblogs.com/zshaox/p/5598284.html
總結
以上是生活随笔為你收集整理的python 学习 [day6]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (王道408考研数据结构)第五章树-第三
- 下一篇: 栈溢出笔记1.8 字符串问题