模块
一、sys
二、os
三、hashlib
四、random
五、re
六、pickle,json
七、configparser
八、XML
九、requests
十、logging alex
十一、系统命令
十二、shutil
十三、paramiko
十四、time
模块,用一砣代码实现了某个功能的代码集合。
类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。
如:os 是系统相关的模块;file是文件操作相关的模块
模块分为三种:
- 自定义模块
- 开源模块
- 内置标准模块(又称标准库)
自定义模块
1.定义模块
.py文件
2.导入模块
1 #导入模块有一下几种方法: 2 import module 3 from module.xx.xx import xx 4 from module.xx.xx import xx as rename 5 from module.xx.xx import * 6 7 8 #导入模块其实就是告诉Python解释器去解释那个py文件 9 ##导入一个py文件,解释器解释该py文件 10 ##导入一个包,解释器解释该包下的 __init__.py 文件 【py2.7】 11 12 #那么问题来了,导入模块时是根据那个路径作为基准来进行的呢?即:sys.path 13 import sys 14 print(sys.path) 15 16 #如果sys.path路径列表没有你想要的路径,可以通过 sys.path.append('路径') 添加。 17 import sys 18 import os 19 project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #相对路径 20 sys.path.append(project_path)
内置模块
内置模块是Python自带的功能,在使用内置模块相应的功能时,需要【先导入】再【使用】
一、sys
用于提供对Python解释器相关的操作:
1 sys.argv 命令行参数List,第一个元素是程序本身路径 2 sys.exit(n) 退出程序,正常退出时exit(0) 3 sys.version 获取Python解释程序的版本信息 4 sys.maxint 最大的Int值 5 sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 6 sys.platform 返回操作系统平台名称 7 sys.stdin 输入相关 8 sys.stdout 输出相关 9 sys.stderror 错误相关x
1 import sys 2 import time 3 4 5 def view_bar(num, total): 6 #显示百分比 7 rate = float(num) / float(total) 8 rate_num = int(rate * 100) 9 r = '\r%d%%' % (rate_num, ) 10 sys.stdout.write(r) 11 sys.stdout.flush() 12 13 14 if __name__ == '__main__': 15 for i in range(0, 100): 16 time.sleep(0.1) 17 view_bar(i, 100)
二、os
用于提供系统级别的操作:
1 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 2 os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd 3 os.curdir 返回当前目录: ('.') 4 os.pardir 获取当前目录的父目录字符串名:('..') 5 os.makedirs('dir1/dir2') 可生成多层递归目录 6 os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推 7 os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirname 8 os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname 9 os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印 10 os.remove() 删除一个文件 11 os.rename("oldname","new") 重命名文件/目录 12 os.stat('path/filename') 获取文件/目录信息 13 os.sep 操作系统特定的路径分隔符,win下为"\\",Linux下为"/" 14 os.linesep 当前平台使用的行终止符,win下为"\t\n",Linux下为"\n" 15 os.pathsep 用于分割文件路径的字符串 16 os.name 字符串指示当前使用平台。win->'nt'; Linux->'posix' 17 os.system("bash command") 运行shell命令,直接显示 18 os.environ 获取系统环境变量 19 os.path.abspath(path) 返回path规范化的绝对路径 20 os.path.split(path) 将path分割成目录和文件名二元组返回 21 os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素 22 os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素 23 os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False 24 os.path.isabs(path) 如果path是绝对路径,返回True 25 os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False 26 os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False 27 os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略 28 os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间 29 os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
三、hashlib
用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
1 import hashlib 2 3 # ######## md5 ######## 4 hash = hashlib.md5() 5 # help(hash.update) 6 hash.update(bytes('admin', encoding='utf-8')) 7 print(hash.hexdigest()) 8 print(hash.digest()) 9 10 11 ######## sha1 ######## 12 13 hash = hashlib.sha1() 14 hash.update(bytes('admin', encoding='utf-8')) 15 print(hash.hexdigest()) 16 17 # ######## sha256 ######## 18 19 hash = hashlib.sha256() 20 hash.update(bytes('admin', encoding='utf-8')) 21 print(hash.hexdigest()) 22 23 24 # ######## sha384 ######## 25 26 hash = hashlib.sha384() 27 hash.update(bytes('admin', encoding='utf-8')) 28 print(hash.hexdigest()) 29 30 # ######## sha512 ######## 31 32 hash = hashlib.sha512() 33 hash.update(bytes('admin', encoding='utf-8')) 34 print(hash.hexdigest())
1 #以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。 2 import hashlib 3 4 # ######## md5 ######## 5 6 hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8")) 7 hash.update(bytes('admin',encoding="utf-8")) 8 print(hash.hexdigest()) 9 10 11 12 #python内置还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密 13 import hmac 14 15 h = hmac.new(bytes('898oaFs09f',encoding="utf-8")) 16 h.update(bytes('admin',encoding="utf-8")) 17 print(h.hexdigest())
四、random
1 import random 2 3 print(random.random()) 4 print(random.randint(1, 2)) 5 print(random.randrange(1, 10))
1 import random 2 checkcode = '' 3 for i in range(4): 4 current = random.randrange(0,4) 5 if current != i: 6 temp = chr(random.randint(65,90)) 7 else: 8 temp = random.randint(0,9) 9 checkcode += str(temp) 10 print checkcode 11 12 # 随机验证码
五、re
python中re模块提供了正则表达式相关操作
match 从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None
1 #match(pattern, string, flags=0) 2 # pattern: 正则模型 3 # string : 要匹配的字符串 4 # falgs : 匹配模式 5 X VERBOSE Ignore whitespace and comments for nicer looking RE's. 6 I IGNORECASE Perform case-insensitive matching. 7 M MULTILINE "^" matches the beginning of lines (after a newline) 8 as well as the string. 9 "$" matches the end of lines (before a newline) as well 10 as the end of the string. 11 S DOTALL "." matches any character at all, including the newline. 12 13 A ASCII For string patterns, make \w, \W, \b, \B, \d, \D 14 match the corresponding ASCII character categories 15 (rather than the whole Unicode categories, which is the 16 default). 17 For bytes patterns, this flag is the only available 18 behaviour and needn't be specified. 19 20 L LOCALE Make \w, \W, \b, \B, dependent on the current locale. 21 U UNICODE For compatibility only. Ignored for string patterns (it 22 is the default), and forbidden for bytes patterns.
1 # 无分组 2 r = re.match("h\w+", origin) 3 print(r.group()) # 获取匹配到的所有结果 4 print(r.groups()) # 获取模型中匹配到的分组结果 5 print(r.groupdict()) # 获取模型中匹配到的分组结果 6 7 # 有分组 8 9 # 为何要有分组?提取匹配成功的指定内容(先匹配成功全部正则,再匹配成功的局部内容提取出来) 10 11 r = re.match("h(\w+).*(?P<name>\d)$", origin) 12 print(r.group()) # 获取匹配到的所有结果 13 print(r.groups()) # 获取模型中匹配到的分组结果 14 print(r.groupdict()) # 获取模型中匹配到的分组中所有执行了key的组
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(pattern, string, flags=0)
# 无分组 r = re.findall("a\w+",origin) print(r) # 有分组 origin = "hello alex bcd abcd lge acd 19" r = re.findall("a((\w*)c)(d)", origin) print(r)
sub(pattern, repl, string, count=0, flags=0) # pattern: 正则模型 # repl : 要替换的字符串或可执行对象 # string : 要匹配的字符串 # count : 指定匹配个数 # flags : 匹配模式
1 # 与分组无关 2 3 origin = "hello alex bcd alex lge alex acd 19" 4 r = re.sub("a\w+", "999", origin, 2) 5 print(r)
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)
IP: ^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$ 手机号: ^1[3|4|5|8][0-9]\d{8}$ 邮箱: [a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+
六、序列化
Python中用于序列化的两个模块
- json 用于【字符串】和 【python基本数据类型】 间进行转换
- pickle 用于【python特有的类型】 和 【python基本数据类型】间进行转换
Json模块提供了四个功能:dumps、dump、loads、load(序、序写、解、读解)
pickle模块提供了四个功能:dumps、dump、loads、load
1 # 序列化 2 3 import pickle 4 user_={ 5 "ming":124, 6 "xuan":345, 7 "wang":4546, 8 } 9 10 # 序列化 11 with open("读写.txt","wb") as f: 12 f.write(pickle.dumps(user_)) 13 14 #序列化,写入 15 with open("读写.txt","wb") as f: 16 pickle.dump(user_,f) 17 18 #序列化 19 with open("读写.txt","rb") as f: 20 users = pickle.loads(f.read()) 21 print(users) 22 23 #序列化,读取 24 with open("读写.txt","rb") as f: 25 users =pickle.load(f) 26 print(users)
七. configparser
configparser用于处理特定格式的文件,其本质上是利用open来操作文件。(2.x版本为ConfigParser)
# 注释1 ; 注释2 [section1] # 节点 k1 = v1 # 值 k2:v2 # 值 [section2] # 节点 k1 = v1 # 值
1 import configparser 2 3 config = configparser.ConfigParser() 4 config.read('xxxooo', encoding='utf-8') 5 6 #1、获取、节点、键、值 7 #所有节点 8 ret = config.sections() 9 print(ret) 10 11 #指定节点下所有的键值对 12 ret = config.items('section1') 13 print(reth) 14 15 #指定节点下所有的建 16 ret = config.options('section1') 17 print(ret) 18 19 #指定节点下指定key的值 20 v = config.get('section1', 'k1') 21 # v = config.getint('section1', 'k1') 22 # v = config.getfloat('section1', 'k1') 23 # v = config.getboolean('section1', 'k1') 24 25 #2、检查、删除、添加节点 26 # 检查 27 has_sec = config.has_section('section1') 28 print(has_sec) 29 30 # 添加节点 31 config.add_section("SEC_1") 32 config.write(open('xxxooo', 'w')) 33 34 # 删除节点 35 config.remove_section("SEC_1") 36 config.write(open('xxxooo', 'w')) 37 38 #3、检查、删除、设置指定组内的键值对 39 # 检查 40 has_opt = config.has_option('section1', 'k1') 41 print(has_opt) 42 43 # 删除 44 config.remove_option('section1', 'k1') 45 config.write(open('xxxooo', 'w')) 46 47 # 设置 48 config.set('section1', 'k10', "123") 49 config.write(open('xxxooo', 'w'))
八、XML pass
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 #利用ElementTree.parse将文件直接解析成xml对象 2 3 from xml.etree import ElementTree as ET 4 # 直接解析xml文件 5 tree = ET.parse("xo.xml") 6 # 获取xml文件的根节点 7 root = tree.getroot() 8 9 10 #利用ElementTree.parse将文件直接解析成xml对象 11 12 from xml.etree import ElementTree as ET 13 # 直接解析xml文件 14 tree = ET.parse("xo.xml") 15 # 获取xml文件的根节点 16 root = tree.getroot()
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.tail 338 339 节点功能一览表
由于 每个节点 都具有以上的方法,并且在上一步骤中解析时均得到了root(xml文件的根节点),so 可以利用以上方法进行操作xml文件。 a. 遍历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) ggg dsfs sdf sdf
sdf
sfd sdf |
九、requests pass
Python标准库中提供了:urllib等模块以供Http请求,但是,它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务
十、logging pass
用于便捷记录日志且线程安全的模块
十一、系统命令 pass
十二、shutil pass
高级的 文件、文件夹、压缩包 处理模块
十三、paramiko pass
paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实。
十四、time pass
时间相关的操作,时间有三种表示方式:
- 时间戳 1970年1月1日之后的秒,即:time.time()
- 格式化的字符串 2014-11-11 11:11, 即:time.strftime('%Y-%m-%d')
- 结构化时间 元组包含了:年、日、星期等... time.struct_time 即:time.localtime()
1 #_*_coding:utf-8_*_ 2 __author__ = 'Alex Li' 3 4 import time 5 6 7 # print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来 8 # print(time.altzone) #返回与utc时间的时间差,以秒计算\ 9 # print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016", 10 # print(time.localtime()) #返回本地时间 的struct time对象格式 11 # print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式 12 13 # print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016", 14 #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上 15 16 17 18 # 日期字符串 转成 时间戳 19 # string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式 20 # print(string_2_struct) 21 # # 22 # struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳 23 # print(struct_2_stamp) 24 25 26 27 #将时间戳转为字符串格式 28 # print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式 29 # print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式 30 31 32 33 34 35 #时间加减 36 import datetime 37 38 # print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925 39 #print(datetime.date.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2016-08-19 40 # print(datetime.datetime.now() ) 41 # print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天 42 # print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天 43 # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时 44 # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分 45 46 47 # 48 # c_time = datetime.datetime.now() 49 # print(c_time.replace(minute=3,hour=2)) #时间替换
1 rhgth 2 jojjo 3 jjjjjjjjjjjjj 4 jjjjj 5 jjjjjjjj 6 jjjjjjjj 7 jjjjjj