第3天

  文件处理

  1 file object = open(file_name,[access_mode],[buffering])


  file_name: file_name参数是一个字符串值,包含要访问的文件的名称。

  access_mode: access_mode 确定该文件已被打开,即模式。读,写等追加。可能值的一个完整列表在下表中给出。这是可选的参数,默认文件访问模式是读(r)
  buffering: 如果缓冲值被设置为0,没有缓冲将发生。如果该缓冲值是1,将在访问一个文件进行行缓冲。如果指定的缓冲值作为大于1的整数,那么缓冲操作将被用指定缓冲器大小进行。这是可选的参数。

  文件访问模式

  模式 描述
  r 以只读方式打开文件,文件指针放在文件开头,这个是默认模式
  rb 以二进制格式读取,文件指针放在文件开头
  r+ 以读取和写入方式打开文件,文件指针在文件开头
  rb+ 以二进制读取和写入方式打开文件
  w 以只写方式打开文件,如果文件存在,则覆盖文件内容,不存在则创建一个新文件
  wb 打开文件以二进制方式写入,文件存在则覆盖,不存在则创建新文件
  w+ 以写入和读取方式打开文件,如果文件存在则覆盖,不存在则创建新文件
  wb+ 以二进制方式写入和读取文件,存在则覆盖现有文件,不存在则创建新文件
  a 以追加方式写入文件末尾,如果不存在则创建该文件
  ab 以二进制格式追加在文件末尾,不存在则创建该文件
  a+ 以追加和读取方式打开文件,如果文件存在,文件指针在文件的末尾,如果不存在,则创建新文件并写入和读取


  文件的操作示例

 1 open_file = open('/tmp/file.txt',r+) #以读取和写入方式打开文件
  2 
  3 open_file.write('hello
') #写入内容,加上换行符,
  4 
  5 open_file.close() #打开文件后,不做操作需要关闭
  6 
  7 #文件操作有以下几种方法
  8 #2.x 方法 ['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
  9 
  10 #3.x 方法['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines']


re.match() #从str的起始位置匹配模式,匹配不成功返回none,使用s.group() or s.groups()获取返回内容。 re.search() #扫描字符串,找到这个 RE 匹配的位置 re.findall() #找到 RE 匹配的所有子串,并把它们作为一个列表返回 re.finditer() #找到 RE 匹配的所有子串,并把它们作为一个迭代器返回

re语法介绍:

# 正则语法
re.match(pattern, string, flags=0)

pattern '匹配的正则表达式'
string  '要匹配的字符串'
flags   '标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等'

# 返回匹配对象
group(num=0) #匹配的整个表达式的字符串,
group()      #可以一次输入多个组号,在这种情况下它将返回一个包含那些组所对应值的元组。
groups()     #返回一个包含所有小组字符串的元组,从 1 到 所含的小组号。

例子:

In [1]: import re

In [2]: s = 'abc,234,dwd,dwd'

In [3]: m = re.match('abc',s,2)

In [7]: m.group()
Out[7]: 'abc'

 

队列

Python中,队列是线程间最常用的交换数据的形式。python中队列区分单向队列和双向队列。单向队列在python2中模块是 import Queue,在python3中是import queue

单向队列

python2中演示:

Queue.Queue()先进先出
# 创建一个队列,指定长度为2,长度小于0为不限制长度
>>> import Queue
>>> s = Queue.Queue(maxsize = 2)
>>>

s.put() 将值放入队列中

  • put()方法将值插入到队尾,
  • put()方法有3个参数,item,block=True,timeout=None

  • item是必须的,为插入项目的值,

  • block是可选的,值为False,当队列满了之后引发Full异常,值为True时,将一直等待队列空出一个单元数据(貌似默认值就是True)

  • timeout 可选, 等待时间,当不指定时间时,队列满了程序会一直等待队列空出一个数据单元,当指定timeout超时时间时,在指定时间内队列没有空出一个数据单元将引发Full异常。

>>> s.put(1,block=False)
>>> s.put(2,block=False)
>>> s.put(3,block=False)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python2.7/Queue.py", line 123, in put
    raise Full
Full
>>>

>>> s.put(1,block=True)
>>> s.put(2,block=True)
>>> s.put(3,block=True)

>>> s.put(1,timeout=2)
>>> s.put(2,timeout=2)
>>> s.put(3,timeout=2)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python2.7/Queue.py", line 134, in put
    raise Full
Full
>>>

s.get() 将值从队列中取出

  • get()方法重队列头删除并返回一个数据单元,参数可选block,timeout
  • block参数值为True和False,当队列为空时,参数True会一直等待直到有数据单元返回,参数False会直接引发Empty异常。
  • timeout指定等待时间
>>> s.get()
1
>>> s.get()
2
>>> s.get(block=False)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python2.7/Queue.py", line 165, in get
    raise Empty
Empty
>>> s.get(timeout=2)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python2.7/Queue.py", line 176, in get
    raise Empty
Empty
>>>

s.qsize() 返回队列的大小

>>> s.qsize()
0

s.empty() 队列为空时返回True

>>> s.empty()
True

s.full()队列满时返回True

>>> s.full()
False
Queue.LifoQueue 后进先出 先进后出
>>> s2 = Queue.LifoQueue(maxsize=2)
>>> s2.put(1)
>>> s2.put(2)
>>> s2.put(3,block=False)
Traceback (most recent call last):
    File "<input>", line 1, in <module>
    File "/usr/lib/python2.7/Queue.py", line 123, in put
        raise Full
Full
#注意取值和存值的顺序
>>> s2.get()
2
>>> s2.get()
1
>>>

#再观察先进先出的取值和存值
>>> s = Queue.Queue(maxsize=2)
>>> s.put(1)
>>> s.put(2)
>>> s2 = Queue.LifoQueue(maxsize=2)
>>> s2.put(1)
>>> s2.put(2)
>>> s.get()
1
>>> s.get()
2
>>> s2.get()
2
>>> s2.get()
1
>>>

python3

在python3中模块名有变化,
In [1]: import queue

In [2]: s = queue.Queue(maxsize=2)

In [3]: s.
s.all_tasks_done    s.get_nowait        s.not_empty         s.qsize
s.empty             s.join              s.not_full          s.queue
s.full              s.maxsize           s.put               s.task_done
s.get               s.mutex             s.put_nowait        s.unfinished_tasks

In [3]: s.put(1)

In [4]: s.put(2)

In [5]: s.put(3,block=False)
---------------------------------------------------------------------------
Full                                      Traceback (most recent call last)
<ipython-input-5-8ebc2086f968> in <module>()
----> 1 s.put(3,block=False)

/usr/lib/python3.4/queue.py in put(self, item, block, timeout)
    131                 if not block:
    132                     if self._qsize() >= self.maxsize:
--> 133                         raise Full
    134                 elif timeout is None:
    135                     while self._qsize() >= self.maxsize:

Full:

双向队列

python3中 deque在collections中 deque,全名double-ended queue)是一种具有队列和栈的性质的数据结构。双端队列中的元素可以从两端弹出,其限定插入和删除操作在表的两端进行

>>> a = collections.deque([])   #创建空列表
>>> a.append(1)                 #从后添加
>>> a
deque([1])
>>> a.append(2)
>>> a.append('a')
>>> a
deque([1, 2, 'a'])
>>> a.appendleft('b')           #从头添加
>>> a
deque(['b', 1, 2, 'a'])
>>>

>>> a.pop()                     #从后取
'a'
>>> a
deque(['b', 1, 2])
>>> a.popleft()                 #从前取
'b'
>>> a
deque([1, 2])
>>>

>>> a.remove(2)                 #删除指定元素
>>> a
deque([1])
>>>

>>> a.extend(['b', 1, 2, 'a'])  #从前扩展队列
>>> a
deque([1, 'b', 1, 2, 'a'])
>>> a.extendleft(['d', 1, 2, 'd']) #从后扩展队列
>>> a
deque(['d', 2, 1, 'd', 1, 'b', 1, 2, 'a'])
>>>

>>> a.reverse()                    #反转队列
>>> a
deque(['a', 2, 1, 'b', 1, 'd', 1, 2, 'd'])
>>>

a.clear()       #清空队列
a.count(n)      #在队列中统计元素的个数,n表示统计的元素
a.rotate(n)      #旋转队列,默认时值为1,由右边开始旋转,负值代表左边旋转,n代表从队列的第一个元素开始,n从1开始计数

collections 系列练习

Counter

set()

集合练习

1.set.add

# 2.set.clear     #添加元素
In [51]: s = set([1,2,3,4,'s'])

In [52]: s.add('d')

In [53]: s
Out[53]: {1, 2, 3, 4, 's', 'd'}

2.set.clear

# 2.set.clear     #从set中移除所有元素
In [54]: s.clear()

In [55]: s
Out[55]: set()

3.set.copy

    #3.set.copy      #返回set的浅拷贝

4.set.difference

#4.set.difference            #返回由两个或多个set中不同的元素(差集)组成一个新set
In [56]: s1 = set([1,2,3,4,5,6])

In [57]: s2 = set(['a','b','c','d'])

In [58]: s1.dif
s1.difference         s1.difference_update

In [60]: s3 = s1.difference(s2)

In [61]: s3
Out[61]: {1, 2, 3, 4, 5, 6}

In [63]: s2
Out[63]: {'a', 'b', 'c', 'd'}

# 上面s1里面的元素在s2中没有,所以s3得到的元素为s1本身
In [64]: s4 = s2.difference(s1)

In [65]: s4
Out[65]: {'a', 'b', 'c', 'd'}
# s4 用s2得到和s3相反的结果

5.set.difference_update

   #5.set.difference_update     #从当前set中移除其它set中所有所有元素。
   In [66]: s4.difference_update(s1)

   In [67]: s4
   Out[67]: {'a', 'b', 'c', 'd'}

   In [68]: s4.difference_update(s2)

   In [69]: s4
   Out[69]: set()

6.set.discard

#6.set.discard               #从set中删除一个元素,如果set中存在该元素
In [70]: s3
Out[70]: {1, 2, 3, 4, 5, 6}

In [71]: s3.discard('a')

In [72]: s3
Out[72]: {1, 2, 3, 4, 5, 6}

In [73]: s3.discard(4)

In [74]: s3
Out[74]: {1, 2, 3, 5, 6}

7.set.intersection 两个集合的交集

#7.set.intersection          #返回两个或多个set的交集,即两个或多个set中都存在的元素
In [91]: s1
Out[91]: {1, 2, 3, 4, 5, 6, 'b', 'a'}

In [92]: s2
Out[92]: {'a', 'b', 'c', 'd'}

In [94]: s3 = s1.intersection(s2)

In [95]: s3
Out[95]: {'a', 'b'}

8.set.intersection_update

#8.set.intersection_update   #更新当前set,只保留那些在当前set和其他set中都存在的
In [106]: s1
Out[106]: {1, 2, 3, 4, 5, 6, 'b', 'a'}

In [107]: s2
Out[107]: {'a', 'b', 'c', 'd'}

In [108]: s1.intersection_update(s2)

In [109]: s1
Out[109]: {'a', 'b'}

9.set.isdisjoint

#9.set.isdisjoint            #如果两个set没有交集,返回true
In [111]: s1
Out[111]: {'a', 'b'}

In [112]: s2
Out[112]: {'a', 'b', 'c', 'd'}

In [113]: s2.isdisjoint(s1)
Out[113]: False

---------

In [115]: s2
Out[115]: {'a', 'b', 'c', 'd'}

In [116]: s3
Out[116]: {1, 2, 3, 4, 5}

In [117]: s3.isdisjoint(s2)
Out[117]: True
10.set.issubset             #判断是否另外一个set包含当前set。
In [118]: s2
Out[118]: {'a', 'b', 'c', 'd'}

In [119]: s3
Out[119]: {1, 2, 3, 4, 5}

In [120]: s2.issu
s2.issubset    s2.issuperset

In [120]: s2.issubset(s3)
Out[120]: False

--------
In [125]: s2
Out[125]: {'a', 'b', 'c', 'd'}

In [126]: s4
Out[126]: {'a', 'b'}

In [127]: s4.issubset(s2)
Out[127]: True

In [128]: s2.issubset(s4)
Out[128]: False

集合练习

下面是一个集合的小练习

def trset():
    '''
     -- set ---
    set练习 将下面两个字典的key来用set来做比较,找出交集,差集,
    1. 要删除   #  new里面没有old里面有的删除
    2. 要更新   #  new里面没有old里面有的增加
    3. 要添加   #  new 和old都有的更新
    '''
 old_dict = {
        "#1":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 80  },
        "#2":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 80  },
        "#3":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 80  },
    }

    new_dict = {
        "#1":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 800 },
        "#3":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 80 },
        "#4":{ 'hostname':"c2", 'cpu_count': 2, 'mem_capicity': 80 },
    }

    old = set(old_dict.keys())
    new = set(new_dict.keys())

    update_set = old.intersection(new)
    delete_set = old.difference(new)
    add_set = new.difference(old)

    print('update:',update_set)
    print('delte:',delete_set)
    print('add:',add_set)

函数练习

python函数根据参数来区分可以分为5种形式:

1.无参数

In [1]: def show():
   ...:     print('a')
   ...:

In [2]:  show()
a

2.有参数

1个参数

In [3]: def show(arg):
   ...:         print(arg)
   ...:

In [4]: show('hello')
hello

2个参数

In [5]: def show(arg0,arg1):
   ...:         print(arg0,arg1)
   ...:

In [6]: show('hello','world')
hello world

3.默认参数

In [7]: def show(arg,arg0='88'):
   ...:         # 默认的参数必须放在最后
   ...:         print(arg,arg0)
   ...:

In [8]: show('dd')
dd 88

In [9]: show('dd','aa')
dd aa

4.指定参数

In [10]: def show(arg,arg0,arg1):
   ....:         print(arg,arg0,arg1)
   ....:

In [11]: show('a','b','c')
a b c

In [12]: show(arg1='a',arg0='b',arg='c')
c b a

5.动态参数

参数转换为元组

In [29]: def show(*arg): #参数转换为元组
   ....:         print(arg,type(arg))
   ....:

In [30]: show('a')
('a',) <class 'tuple'>

In [31]: show(1,23,4,'sdf')
(1, 23, 4, 'sdf') <class 'tuple'>

参数转换为字典

In [37]: def show(**arg): #参数转换为字典
        pass
        print(arg,type(arg))
   ....:

In [38]: show(a='v')
{'a': 'v'} <class 'dict'>

In [39]: show(a='v',k1='v1',k2='v2')
{'a': 'v', 'k1': 'v1', 'k2': 'v2'} <class 'dict'>

同时转换为tuple和dict

#传参形式1
In [45]: def show(*args,**kwargs):
        pass
        print(args,type(args))
        print(kwargs,type(kwargs))
   ....:

In [46]: show(2,3,4,5,'a','d',k1='v1',k2='v2')
(2, 3, 4, 5, 'a', 'd') <class 'tuple'>
{'k1': 'v1', 'k2': 'v2'} <class 'dict'>
传参形式2
In [47]: li = [2,3,4,5,'a']
In [48]: d = {'k1':'v1','k2':'v2'}

In [49]:

In [49]: show(li,d)
([2, 3, 4, 5, 'a'], {'k1': 'v1', 'k2': 'v2'}) <class 'tuple'>
{} <class 'dict'>
#传参形式3
In [50]: show(*li,**d)
(2, 3, 4, 5, 'a') <class 'tuple'>
{'k1': 'v1', 'k2': 'v2'} <class 'dict'>
原文地址:https://www.cnblogs.com/sunface/p/5181056.html