模块补充 、迭代器和 生成器

 

 内置函数vase()

print(vars())

print(type(vars()),vars())

type()函数是返回传递变量的类型。如果传递变量是字典那么它将返回一个字典类型。

__doc__  # py文件的注释

例:

"""
   我是index注释

"""

print(__doc__)

__file__ #本身自己文件路径

print(__file__)

__package__ #当前文件 None

       #导入的其他文件所在的包,用 . 划分

form 文件路径 import 文件
print
(文件.__package__)

__cached__ #缓存 (了解)

__name__

 1 from lib import s1
 2 form lib import s2
 3 
 4 def execute():
 5     print("执行")
 6     s1.f1()
 7     s2.f1()
 8 #只有 执行 python xx.py 时 if__name__ =="__main__": 否则是文件名
 9 
10 if __name__ == "__main__":
11     execute()

sys模块

sys.path python默认去根据[]的路径去找到模块

 1 import sys
 2 print(sys.path.append())
 3 print()
 4 
 5 
 6 
 7 import os 
 8 import sys
 9 
10 p1 = os.path.dirname(__file__)
11 p2 = "lib"
12 
13 my_dir = os.path.join(p1,p2) #拼接起来
14 sys.path.append(my_dir)
15 for i in sys.path:
16     print(i)

json模块

json.dumps与json.loads两个用处:

json.dumps() #将python的python基本数据类型装换成字符串

json.loads用于将字典,列表,元组形式的字符串,转换成相应的字典,列表,元组

 1 s = '{"desc":"invilad-citykey","status":1002}'  #疑式字典的外边用单引号,内部必须要用双引号。
 2 l = "[11,22,33,44]"
 3 
 4 import json
 5 
 6 
 7 # result = json.loads(s)
 8 # print(result,type(result)
 9 #json.loads用于将字典,列表,元祖形式的字符串,转换成相应的字典,列表,元祖。 ***注意json.losds内部必须用双引号***
10 
11 result = json.loads(l)
12 print(result,type(result))
13 输出[11, 22, 33, 44] <class 'list'>
14 
15 
16 
17 
18 user_list = ["alex","eric","tomy"]
19 import json
20 
21 s = json.dumps(user_list)
22 #json.dumps() #将python的python基本数据类型装换成字符串
23 
24 print(s,type(s))
25 #输出["alex", "eric", "tomy"] <class 'str'>

了解:json.dump与json.load

import json

dic = {'k1':123,'k2':'v2'}
json.dump(dic,open('db','w'))
#读内容
#字符串转换成字典
r = json.load(open('db','r'))
print(r,type(r))
import json
dic = {'k1':123,'k2':456}
json.dump(dic,open('db','w')) 
r = json.load(open('db','r'))
print(r,type(r))

requests模块

requests,发送http请求(用python模拟浏览器浏览网页)

1 import requests
2 
3 requests = requests.get("http://www.weather.com.cn/adat/sk/101010500.html")  #浏览天气
4 requests.encoding = "utf-8"
5 result = requests.text
6 print(result)

http请求和XML实例

 检测QQ是否在线:

 1 import requests
 2 # 使用第三方模块requests发送HTTP请求,或者XML格式内容
 3 r = requests.get('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=2218308808')
 4 result = r.text #字符串类型
 5 
 6 from xml.etree import ElementTree as ET
 7 #解析XML格式内容
 8 #XML接收一个参数:字符串,格式化为特殊的对象
 9 node = ET.XML(result)
10 
11 #获取内容
12 if node.text == "Y":
13     print("在线")
14 else:
15     print("离线")

查看火车停靠信息:

 1  1 import requests
 2  2 from xml.etree import ElementTree as ET
 3  3 
 4  4 #使用第三模块requests发送HTTP请求,或者XML格式内容
 5  5 r = requests.get('http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=K234&UserID=')
 6  6 result = r.text
 7  7 
 8  8 #解析XML格式内容
 9  9 root = ET.XML(result)
10 10 
11 11 for node in root.iter('TrainDetailInfo'):
12 12     #print(node.tag, node.attrib)
13 13     print(node.find('TrainStation').text, node.find('StartTime').text)
14 14     #print(node.find('TrainStation').text, node.find('StartTime').text,node.tag,node.attrib)

XML

XML是实现不同语言或程序之间进行数据交换

tag #根节点

attrib #标签属性

find  #查找

iter  #可迭代的

set  #设置属性

defau.xml文件

<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year age="19" name="alex">2040</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year age="19" name="alex">2043</year>
        <gdppc>59900</gdppc>
        <neighbor direction="N" name="Malaysia" />
    </country>
    </data>
View Code

1,解析XML

1)用ElementTree.XML将字符串解析成xml对象:

1 form xml.etree import ElementTree as ET
2 
3 str_xml = open('defau.xml', 'r').read() #打开daefau.xml文件,读取xml内容
4 
5 root = ET.XML(str_xml) #将支付串解析成xml对象,root指代xml文件节点

2)用ElementTree.parse将文件直接解析成xml对象

1 form xml.etree import ElementTree as ET
2 
3 tree = ET.parse("defau.xml") #直接解析xml文件
4 
5 root = tree.getroot() #获取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.tail
节点的所有操作
2.1获取所有XML文档所有内容
1from xml.etree import ElementTree as ET

str_xml = open('defau.xml','r').read() #打开文件,读取xml内容

root = ET.XML(set_xml) #将字符串解析成xml对象,root代指xml文件的根节点


2from xml.etree import ElementTree as ET
root = ET.XML(open('defau.xml','r',encoding='utf-8').read()) #将字符串解析成xml的对象,root代指xml文件根节点;打开文件,读取xml内容
print(root.tag)# 打印顶级标签
 
for node in root:  #循环出xml文档的第二层
    print(node,type(node)) #节点标签
    print(node
 2.2获取XML中指定的节点
1from xml.etree import ElementTree as ET

#str_xml = open('defau.xml', 'r').read() #打开文件,读取xml文件内容

#root = ET.XML(str_xml) #将字符串解析成xml对象,root代指xml文件的根节点



2from xml.etree import ElementTree as ET

tree = ET.parse("defau.xml") #直接解析xml文件

root = tree.getroot #获取xml文件的根节点

print(root.tag) #顶级标签

for node in root .iter('year'): #获取xml中所有year节点

    print(node.tag,node.text) #节点的标签名和内容
 
2.3修改节点内容

字符串方式,修改,保存

 1 from xml.etree import ElementTree as ET
 2 
 3 #打开并解析文件内容
 4 tree = ET.parse("defau.xml")
 5 
 6 root = tree.getroot()  #获取根节点

7 for node in root .iter('year'):#循环所有year节点 8 new_year = int(node.text) + 1 #每次获取这个节点的值加一,重新赋值 9 node.text = str(new_year) #设置属性 10 node.set('name','alex') #添加节点内容 11 node.set('age','19') # 12 del node.attrib['name'] #删除节点的属性 13 14 tree.write("defau.xml") #写入文件
 1 from xml.etree import ElementTree as ET #(as表示ET是ElementTree的别名)
 2 
 3 #直接解析xml文件
 4 tree = ET.parse("defau.xml")
 5 
 6 #获取xml文件的根节点,Element类型
 7 root = tree.getroot() #获取xml根节点
 8 
 9 print(root.tag) #获取根标签
10 print(root.attrib) #标签的属性
11 print(root.text) #获取根内容
12 #
13 #创建节点,Element类型
14 # son = root.makeelement('tt',{'kk':"vv"}) #在根节点下创建一个子节点
15 
16 # s = son.makeelement('tt',{'kk':"123123"}) #在son下建一个子节点
17 
18 son = ET.Element('pp',{'kk':"vv"})
19 ele2 = ET.Element('pp',{'kk':"123123"})
20 son.append(ele2)
21 root.append(son)
22 
23 
24 # son.append(s) #添加到son的节点下
25 
26 # root.append(son)#添加到根节点下
27 
28 tree.write("out.xml") #内存中的xml写入文件中
2.4删除节点
 1 from xml.etree import ElementTree as ET
 2 
 3 tree = ET.parse("defau.xml")# 直接解析xml文件
 4 
 5 root = tree.getroot()# 获取xml文件的根节点
 6 
 7 #操作文件
 8 
 9 print(root.tag)# 顶层标签
10 
11 for country in root.findall('country'):# 遍历data下的所有country节点
12   
13     rank = int(country.find('rank').text)  # 获取每一个country节点下rank节点的内容
14 
15     if rank > 50:
16         
17         root.remove(country)# 删除指定country节点
18 
19 tree.write("defau.xml", encoding='utf-8')#解析文件方式打开,删除,保存

3,创建XML文档

 1 from xml.etree import ElementTree as ET
 2 root = ET.Element('family',{"age":"16"})
 3 
 4 # son = ET.Element('family',{"age":"18"})
 5 # son = root.makeelement('family',{"age":"19"})
 6 # root.append(son)
 7 ET.SubElement(root,'family',{"age":"19"})
 8 son = ET.SubElement(root,'family',{"age":"十一"})
 9 ET.SubElement(son,'family',{"age":"1"})
10 
11 tree = ET.ElementTree(root)
12 
13 
14 tree.write("out.xml",encoding='utf-8',xml_declaration=True)

原生保存的XML时默认无缩进,设置缩进, 需要修改保存方式

from xml.etree import ElementTree as ET
from xml.dom import minidom


def prettify(elem):
    """将节点转换成字符串,并添加缩进。
    """
    rough_string = ET.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="	")

# 创建根节点
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()
xml格式的缩进

4,命名空间

 1 from xml.etree import ElementTree as ET
 2 
 3 ET.register_namespace('com',"http://www.company.com") #some name
 4 
 5 # build a tree structure
 6 root = ET.Element("{http://www.company.com}STUFF")
 7 body = ET.SubElement(root, "{http://www.company.com}MORE_STUFF", attrib={"{http://www.company.com}hhh": "123"})
 8 body.text = "STUFF EVERYWHERE!"
 9 
10 # wrap it in an ElementTree instance, and save as XML
11 tree = ET.ElementTree(root)
12 
13 tree.write("page.xml",
14            xml_declaration=True,
15            encoding='utf-8',
16            method="xml")
17 
18 命名空间
命名空间

configparser模块

用于处理特定格式的文件,其本质是例用open来操作文件。

1 [section1]  # 节点
2 k1 = v1      #
3 k2:v2         #
4 
5 [section2]   # 节点
6 k3 = v3       #
7 k4:v4          #
特定格式
[kaixin]
age = 123
gender = 0
xxx = oo

[yongcong]
age = 19
gender = "man"


[section1] 
k1 = v1    
k2:v2      

[section2] 
k3 = v3   
k4:v4
ini文件

1)获取所有节点

1 import configparser
2 con = configparser.ConfigParser() #获取所有节点
3 
4 con.read("ini",enconding = 'utf-8')
5 
6 result = con.sections()
7 
8 print(result)

2)获取指定节点的键

1 impor configparser
2 con = configparser.ConfigParser() #获取所有节点
3 
4 con.read("ini",encoding='utf-8')#读取所有节点
5 
6 ret = con.options('kaixin')#获取指定节点“kaixin”的键
7 
8 print(ret)

3)获取指定节点的键值对

1 import configparser
2 
3 con = configparser.ConfigParser()
4 
5 con.read('ini',encoding='utf-8')
6 
7 ret = con.items('kaixin') #获取指定节点“kaixin”的键值对
8 
9 print(ret)

4)获取指定节点下的指定key的值

 1 import configparser
 2 config = configparser.ConfigParser()
 3 config.read('ini', encoding='utf-8')
 4 
 5 
 6 # v = config.get('kaixin', 'age')#获取指定节点下指定key的值
 7 # v = config.getint('kaixin', 'age') #以整数形式
 8 # v = vconfig.getfloat('kaixin', 'age')#以浮点数形式
 9 v = config.getboolean('kaixin', 'age') #以布尔形式(键的值必须是True或False否则报错)
10 
11 print(v)

5)检查、删除、添加节点

 1 import configparser
 2 
 3 con = configparser.ConfigParser()
 4 con.read('ini',encoding='utf-8')
5 #检查 6 # n = con.has_section('kaixin')#检查有没有节点 7 # print(n)
8 #添加 9 # con.add_section("cong") #添加节点 10 # con.write(open('ini','w'))#打开文件写入

11 #删除 12 # con.remove_section("cong") #删除"cong"节点 13 # con.write(open('ini','w'))

6)检查、删除、设置指定节点的键值对

 1 import configparser
 2 
 3 con= configparser.ConfigParser()
 4 con.read('ini',encoding='utf-8')
 5 
 6 #检查
 7 # m = con.has_option('kaixin','age') #has_option 检查指定键值对
 8 # print(m)
 9 
10 #删除
11 # m = con.remove_option('kaixin','age') #remove_option删除指定节点的键值对
12 # con.write(open('kaixin','w'))
13 
14 #设置
15 con.set('kaixin','k6','678') #set添加键值对到指定节点
16 con.write(open('ini','w'))

logging模块

用于便捷记录日志,且线程安全的模块

 1 import logging
 2 logging .basicConfig(filename='log.log',
 3                      format= '%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
 4                      datefmt = '%Y-%m-%d %H:%M:%S %p',
 5                      level=10)#只有当前写等级大于日志等级时,日志文件才被记录
 6 """#日志等级:
 7 CRITTCAL = 50
 8 FATAL = CRITTICAL
 9 ERROR = 40
10 WARNING = 30
11 WARN = WARNING
12 INFO = 20
13 DEBUG = 10
14 NOTSET = 0
15 """
16 
17 logging.critical('c')
18 logging.fatal('w')
19 logging.error('c')
20 logging.warning('f')
21 logging.info('k')
22 logging.debug('n')
23 logging.log(logging.INFO,'333')

 把日志备份到另个文件:

 1 import logging
 2 
 3 #创建文件
 4 file_1_1 = logging.FileHandler('l1_1.log','a')
 5 
 6 #创建格式
 7 fmt = logging.Formatter(fmt= "%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s")
 8 
 9 #文件应用格式
10 file_1_1.setFormatter(fmt)
11 
12 file_1_2 = logging.FileHandler('l1_2.log','a')
13 fmt= logging.Formatter()
14 file_1_2.setFormatter(fmt)
15 
16 logging1 = logging.Logger('s2',level=logging.ERROR)#'s2'给日志文件定义名字
17 
18 logging1.addHandler(file_1_1)
19 logging1.addHandler(file_1_2)
20 
21 
22 #写日志
23 logging1.critical('123456')

shutil

高级的文件,文件夹、压缩包处理模块

1)shutil.copyfileobj(fsrc, fdst[, length])

将文件内容拷贝到另一个文件中

import shutil
shutil.copyfileobj(open('defau.xml','r'),open('sehh.xml','w')) #清空后写入

import shutil
shutil.copyfileobj(open('defau.xml','r'),open('sehh.xml','a'))#追加进去
2)shutil.copyfile(src, dst)

拷贝文件

import shutil
shutil.copyfile('defau.xml','sehh.xml') #把‘defau.xml’文件拷贝到‘sehh.xml’文件中.没有文件就创建
3)shutil.copymode(src, dst)

仅拷贝权限。内容、组、用户均不变

import shutil
shutil.copymode('defau.xml','sehh.xml') #之拷贝权限,不拷贝文件内容 。如果没有文件报错
4)shutil.copystat(src, dst)

拷贝状态的信息,包括:mode bits, atime, mtime, flags

import shutil
shutil.copystat('defau.xml','sehh')#拷贝状态信息
5)shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)

递归的去拷贝文件夹

import shutil
 
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
import shutil
import os
# print(os.path.dirname(os.path.dirname(__file__))+"/da")
# exit()
shutil.copytree(os.path.dirname(os.path.dirname(__file__))+"/da",'da33',symlinks=True,ignore=shutil.ignore_patterns('*.pyc','tmp'))
6)shutil.rmtree(path[, ignore_errors[, onerror]])

递归的去删除文件

import shutil
 
shutil.rmtree('day1')

7)shutil.move(src, dst)

递归的去移动文件,它类似mv命令,其实就是重命名。

import shutil
 
shutil.move(day1', 'day2')

8)shutil.make_archive(base_name, format,...)

创建压缩包并返回文件路径,例如:zip、tar

创建压缩包并返回文件路径,例如:zip、tar

base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,

  • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
  • root_dir: 要压缩的文件夹路径(默认当前目录)
  • owner: 用户,默认当前用户
  • group: 组,默认当前组
  • logger: 用于记录日志,通常是logging.Logger对象
1 #将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
2 import shutil
3 ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
4   
5   
6 #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
7 import shutil
8 ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')

shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:

import zipfile

# 压缩
# z = zipfile.ZipFile('laxi.zip', 'w')
# z.write('log.log')
# z.write('first.xml')
# z.close()

# 添加一个文件
# z = zipfile.ZipFile('laxi.zip', 'a')
# z.write('first1.xml')
# z.write('a/a') # 将a目和其下面的a文件一同录压缩到里面 如果存在会保存,但是仍然压缩进入
# z.write('b/c') # 将b目录和其下面的c文件一同压缩到里面
# z.write('b/b') # 将b目录和其下面的c文件一同压缩到里面
# z.close()

# 解压
# z = zipfile.ZipFile('laxi.zip', 'r')
# z.extractall("log.log") # 解压所有文件到log.log目录
# z.extract("log.log") # 解压单个文件log.log到当前目录 文件如果存在也无报错
# z.extract("first.xml") # 解压单个文件log.log到当前目录 文件如果存在也无报错
# z.close()

zipfile解压缩
zipfile解压缩
 1 import tarfile,os
 2 # 压缩
 3 # tar = tarfile.open("your.tar",'w') # 已存在不报错
 4 # tar.add(os.path.dirname(__file__),arcname="nonosd") #将前面的目录重新改名为nonosd目录名 归档到your.tar中
 5 # tar.add("first.xml",arcname="first.xml") #将前面的目录重新改名为nonosd目录名 归档到your.tar中
 6 # tar.close()
 7 
 8 # tar = zipfile.ZipFile('laxi.zip', 'a')
 9 # tar.write('first1.xml')
10 # tar.write('a/a') # 将a目和其下面的a文件一同录压缩到里面 如果存在会保存,但是仍然压缩进入
11 # tar.write('b/c') # 将b目录和其下面的c文件一同压缩到里面
12 # tar.write('b/b') # 将b目录和其下面的c文件一同压缩到里面
13 # tar.close()
14 
15 # 压缩
16 tar = tarfile.open('your.tar','r')
17 # print(tar.getmembers())
18 print(tar.getnames()) #查看所有的文件名
19 tar.extract('first.xml') #解压单个文件
20 tar.extractall(path="a/") # 解压所有到 path
21 tar.close()
22 
23 tarfile解压缩
tarfile解压缩

迭代器

迭代器是访问集合元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束

特点:

  1. 访问者不需要关心迭代器内部的结构,仅需通过next()方法不断去取下一个内容
  2. 不能随机访问集合中的某个值 ,只能从头到尾依次访问
  3. 访问到一半时不能往回退
  4. 便于循环比较大的数据集合,节省内存
 1 a = iter([1,2,3,4,5])
 2 print(a)
 3 # <list_iterator object at 0x101402630>
 4 print(a.__next__())#输出 1
 5 
 6 print(a.__next__())#输出 2
 7 
 8 print(a.__next__())# 输出3
 9 
10 print(a.__next__())# 输出4
11 
12 print(a.__next__())# 输出5
13 
14 print(a.__next__()) #超过后就会报错

生成器 

一个函数调用时返回一个迭代器,那这个函数就叫做生成器(generator);如果函数中包含yield语法,那这个函数就会变成生成器

特点:

在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。

 1 def xrange():  #带yield为生成器函数
 2     print(11)
 3     yield 1
 4 
 5     print(22)
 6     yield 2
 7 
 8     print(33)
 9     yield 3
10 
11 r = xrange() #仅获取到第一个生成器
12 #生成器的__next__方法
13 ret = r.__next__() #获取第一次
14 print(ret)
15 
16 ret = r.__next__()#记住上次执行的,进行寻找下一个yield,再进行执行。
17 print(ret)
18 
19 ret = r.__next__()#获取第三次,如果上面没有yield可执行就报错,
20 print(ret)

 示例:

 1 def xrangs(n):
 2     start = 0
 3     while True:
 4         if start > n:
 5             return
 6         yield start
 7         start += 1
 8 
 9 obj = xrangs(5)
10 n1 = obj.__next__()
11 n2 = obj.__next__()
12 n3 = obj.__next__()
13 n4 = obj.__next__()
14 n5 = obj.__next__()
15 n6 = obj.__next__()
16 print(n1,n2,n3,n4,n5,n6)
17 
18 输出:
19 0 1 2 3 4 5

详细请参考:http://www.cnblogs.com/wupeiqi/articles/4963027.html

      http://www.cnblogs.com/wupeiqi/articles/5484747.html

原文地址:https://www.cnblogs.com/kongqi816-boke/p/5526343.html