一、文件系统和文件

1、文件系统和文件

文件系统是OS用于明确磁盘或分区上的文件的方法和数据结构——即在磁盘上组织文件的方法

计算机文件(或称文件、电脑档案、档案),是存储在某种长期储存设备或临时存储设备中的一段数据流,并且归属于计算机文件系统管理之下

概括来讲:

       文件是计算机中由OS管理的具有名字的存储区域

       在Linux系统上,文件被看做是字节序列


2、linux文件系统组件的体系结构

wKioL1fcuJzgMDmgAAEBsoQn_y4470.png


3、Python打开文件

Python内置函数open()用于打开文件和创建文件对象

语法格式:

        open(name[,mode[,bufsize]])

open方法可以接收三个参数:文件名、模式和缓冲区参数

open函数返回的是一个文件对象

mode:指定文件的打开模式

bufsize:定义输出缓存

      0表示无输出缓存

      1表示使用缓冲

      负数表示使用系统默认设置

       正数表示使用近似指定大小的缓冲


4、文件的打开模式

简单模式:

       r: 只读   以读的方式打开,定位到文件开头

                 open(‘/var/log/message.log’,’r’)

       w: 写入   以写的方式打开,不能读,定位到文件开头,会清空文件内的数据

       a: 附加   以写的方式打开,定位到文件末尾

在模式后使用“+”表示同时支持输入、输出操作

        如r+、w+和a+

在模式后附加“b”表示以二进制方式打开

        如rb、wb+

In [4]: file.
file.close       file.isatty      file.read        file.tell
file.closed      file.mode        file.readinto    file.truncate
file.encoding    file.mro         file.readline    file.write
file.errors      file.name        file.readlines   file.writelines
file.fileno      file.newlines    file.seek        file.xreadlines
file.flush       file.next        file.softspace   


In [6]: f1=open('/etc/passwd','r')

In [7]: f1
Out[7]: <open file '/etc/passwd', mode 'r' at 0x21824b0>

In [8]: print f1
<open file '/etc/passwd', mode 'r' at 0x21824b0>

In [9]: type(f1)
Out[9]: file



In [10]: f1.next
Out[10]: <method-wrapper 'next' of file object at 0x21824b0>

In [11]: f1.next()   #文件也是可迭代对象,
Out[11]: 'root:x:0:0:root:/root:/bin/bash\n'

In [12]: f1.next()
Out[12]: 'bin:x:1:1:bin:/bin:/sbin/nologin\n'


In [22]: f1.close()      #关闭文件,

In [23]: f1.next()      #文件被关闭后,不能再读取数据
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-23-4a9d57471e88> in <module>()
----> 1 f1.next()

ValueError: I/O operation on closed file
In [50]: f1=open('/etc/passwd','r')

In [51]: f1.
f1.close       f1.isatty      f1.readinto    f1.truncate
f1.closed      f1.mode        f1.readline    f1.write
f1.encoding    f1.name        f1.readlines   f1.writelines
f1.errors      f1.newlines    f1.seek        f1.xreadlines
f1.fileno      f1.next        f1.softspace   
f1.flush       f1.read        f1.tell        

In [51]: f1.readl
f1.readline   f1.readlines  

In [51]: f1.readline
Out[51]: <function readline>

In [52]: f1.readline()
Out[52]: 'root:x:0:0:root:/root:/bin/bash\n'

In [53]: f1.readlines()
Out[53]: 
['bin:x:1:1:bin:/bin:/sbin/nologin\n',
 'daemon:x:2:2:daemon:/sbin:/sbin/nologin\n',
 'adm:x:3:4:adm:/var/adm:/sbin/nologin\n',
 'lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n',
 'sync:x:5:0:sync:/sbin:/bin/sync\n',
 'shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n',
 'halt:x:7:0:halt:/sbin:/sbin/halt\n',
 'mail:x:8:12:mail:/var/spool/mail:/sbin/nologin\n',
 'uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin\n',
 'operator:x:11:0:operator:/root:/sbin/nologin\n',
 'games:x:12:100:games:/usr/games:/sbin/nologin\n',
 'gopher:x:13:30:gopher:/var/gopher:/sbin/nologin\n',
 'ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin\n',
 'nobody:x:99:99:Nobody:/:/sbin/nologin\n',
 'dbus:x:81:81:System message bus:/:/sbin/nologin\n',
 'vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin\n',
 'saslauth:x:499:76:"Saslauthd user":/var/empty/saslauth:/sbin/nologin\n',
 'postfix:x:89:89::/var/spool/postfix:/sbin/nologin\n',
 'haldaemon:x:68:68:HAL daemon:/:/sbin/nologin\n',
 'sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin\n']

In [54]:

读取文件的指针:

In [57]: f1.tell()    #查看当前指针在文件中位置,返回的事,已读文件字节数
Out[57]: 949
In [69]: help(f1.seek)


Help on built-in function seek:

seek(...)
    seek(offset[, whence]) -> None.  Move to new file position.  
  #offse 偏移量,默认是0  whence从什么位置偏移,0表示从文件头开始偏移,1表示从当前位置开始偏移,2表示从文件尾开始偏移,默认是0     
    
    Argument offset is a byte count.  Optional argument whence defaults to
    0 (offset from start of file, offset should be >= 0); other values are 1
    (move relative to current position, positive or negative), and 2 (move
    relative to end of file, usually negative, although many platforms allow
    seeking beyond the end of a file).  If the file is opened in text mode,
    only offsets returned by tell() are legal.  Use of other offsets causes
    undefined behavior.
    Note that not all file objects are seekable.
(END) 

In [72]: f1.seek(0)          #没有指定whence默认是0从文件首部偏移0

In [73]: f1.tell()
Out[73]: 0
In [29]: help(file.read)

Help on method_descriptor:

read(...)
    read([size]) -> read at most size bytes, returned as a string.
    
    If the size argument is negative or omitted, read until EOF is reached.
    Notice that when in non-blocking mode, less data than what was requested
    may be returned, even if no size parameter was given.
In [82]: f1.read(10)        #返回最多10个字节的字符串
Out[82]: 'root:x:0:0'

In [83]: f1.tell()
Out[83]: 10


In [88]: f1.name
Out[88]: '/etc/passwd'


5、文件方法

wKioL1fcuZ3TD7fCAAI8vu9Z7x8038.png

文件对象维护它所打开文件的状态,其tell()方法返回当前在所打开的文件中的位置

read()方法用于将文件读进单一字符串,也可以为其指定要读取的字节数

readline():可以读取下一行到一个字符串,包括行尾的结束符

readlines():则读取整个文件的所有行至以行为单位的字符串列表中

write(aString):输出字节字符串到文件

writelines(aList):用于把列表内所有字符串写入文件

f.isatty():是否是终端设备文件

f.truncate:截取最大指定字节


注意:

       文件方法read()等在读取文件时,会一并读取其行结束符

       文件方法write()执行写出操作时,不会自动为其添加行结束符   


6、文件对象属性

wKiom1fcukrT4COtAACwzuToiHo688.png


with语法

     2.5开始支持with语法

  用于需要打开、关闭成对的操作

     可以自动关闭打开的对象     

语法:

      with open_expr as obj:

             expression

In [90]: f = open("/tmp/passwd","r+")

In [91]: f.closed
Out[91]: False

In [92]: with open("/tmp/passwd","r+") as f:
    pass
   ....: 

In [93]: f.closed
Out[93]: True


二、python文本处理

1、基本字符串处理

 1)字符串分隔和连接

  str.split()     分隔

  str.rsplit()   从右边开始分隔

In [11]: s1="xie xiao jun"


In [13]: help(s1.split)         


Help on built-in function split:

split(...)
    S.split([sep [,maxsplit]]) -> list of strings   #sep为分隔符,默认为空格  最大分隔次数
    
    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are removed
    from the result.
(END) 


In [12]: s1.spli
s1.split       s1.splitlines  

In [12]: s1.split()
Out[12]: ['xie', 'xiao', 'jun']

In [16]: s1.split("",2)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-f3d385e69a09> in <module>()
----> 1 s1.split("",2)

ValueError: empty separator

In [17]: s1.split(" ",2)
Out[17]: ['xie', 'xiao', 'jun']

In [18]: s1.split(" ",1)
Out[18]: ['xie', 'xiao jun']

In [26]: s1.split("x")
Out[26]: ['', 'ie ', 'iao jun']

In [27]: s1
Out[27]: 'xie xiao jun'

In [28]: s1.split("i")
Out[28]: ['x', 'e x', 'ao jun']

In [29]: s1.split("n")
Out[29]: ['xie xiao ju', '']



In [35]: s1.rsplit
s1.rsplit

In [37]: s1.rsplit()                #当设置的分隔次数足够的话rsplit和split没区别
Out[37]: ['xie', 'xiao', 'jun']

In [38]: s1.rsplit(" ",1)          #当设置的分隔次数不够时,rsplit从右边开始分隔
Out[38]: ['xie xiao', 'jun']

In [39]: s1.split(" ",1)
Out[39]: ['xie', 'xiao jun']

join()   +   连接

In [57]: s1
Out[57]: 'xie xiao jun'

In [58]: s2
Out[58]: 'aa bb cc dd ee'

In [59]: ",".join(s1)
Out[59]: 'x,i,e, ,x,i,a,o, ,j,u,n'

In [60]: "-".join(s1)
Out[60]: 'x-i-e- -x-i-a-o- -j-u-n'

In [67]: 'xie' + "jun"
Out[67]: 'xiejun'

 2)字符串格式化

 占位符替换  %s  %d|%i %f

In [75]: "adfas%s" % "hello"
Out[75]: 'adfashello'

In [76]: "adfas %s" % "hello"
Out[76]: 'adfas hello'

In [77]: "adfas %s " % "hello"
Out[77]: 'adfas hello '

In [78]: "adfas %s %s%s" % "hello"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-78-97faba8d8356> in <module>()
----> 1 "adfas %s %s%s" % "hello"

TypeError: not enough arguments for format string

In [80]: "adfas %s %s%s" % ("hello","A","B")  #站位符和元祖的元素个数要相同
Out[80]: 'adfas hello AB'

 3)字符串查找

  str.find()   查找

In [90]: help(s1.find)

Help on built-in function find:

find(...)
    S.find(sub [,start [,end]]) -> int
    
    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.
    
In [102]: s1.find("i")       #元素第一次出线的位置
Out[102]: 1    

In [101]: s1.find("i",4,8)
Out[101]: 5

4)字符串替换

str.replace()

In [104]: s1.replace("x","X")
Out[104]: 'Xie Xiao jun'

In [105]: s1.replace("x","X",1)
Out[105]: 'Xie xiao jun'

 5)str.strip()   移除字符串首尾的空白字符

       str.rstrip()   只去除右边的空白字符

       str.strip()     只去除左边的空白字符

In [21]: s2 = ' xie xiao jun '

In [22]: s2
Out[22]: ' xie xiao jun '

In [23]: s2.st
s2.startswith  s2.strip       

In [23]: s2.strip()
Out[23]: 'xie xiao jun'

In [24]: s2.r
s2.replace     s2.rindex      s2.rpartition  s2.rstrip      
s2.rfind       s2.rjust       s2.rsplit      

In [24]: s2.rstrip()
Out[24]: ' xie xiao jun'

In [25]: s2.l
s2.ljust   s2.lower   s2.lstrip  

In [25]: s2.lstrip()


三、os模块

目录不属于文件对象,输于文件系统,和文件系统打交道,要使用os模块

os模块常用的方法:

1、目录

     getcwd():获取当前工作目录       

        chdir():切换工作目录

        chroot():设定当前进程的根目录

        listdir():列出指定目录下的所有文件名

        mkdir():创建指定目录

        makedirs():创建多级目录

        rmdir():删除目录

        removedirs():删除多级目录

In [1]: import os

In [4]: help(os.mkdir)


Help on built-in function mkdir in module posix:

mkdir(...)
    mkdir(path [, mode=0777])
    
    Create a directory.
(END) 

In [2]: os.mkdir('/tmp/test')

In [3]: ls /tmp
passwd  vgauthsvclog.txt.0  yum_save_tx-2016-09-02-17-11cyWWR1.yumtx
test/   vmware-root/        yum_save_tx-2016-09-21-23-45jB1DoO.yumtx

In [6]: os.getcwd()
Out[6]: '/root'

In [7]: os.c
os.chdir          os.chroot         os.confstr        os.curdir
os.chmod          os.close          os.confstr_names  
os.chown          os.closerange     os.ctermid        

In [8]: os.chdir('/tmp')

In [9]: os.getcwd()
Out[9]: '/tmp'

In [10]: os.stat('test')
Out[10]: posix.stat_result(st_mode=16877, st_ino=522528, st_dev=2050L, st_nlink=2, st_uid=0, st_gid=0, st_size=4096, st_atime=1474959686, st_mtime=1474959686, st_ctime=1474959686)

2、文

        mkfifo():创建匿名管道

        mknod():创建设备文件

        remove():删除文件

        unlink():删除链接文件

        rename():重命名

        stat():返回文件状态信息,适用于文件和目录

        symlink(): 创建链接

        utime():更新时间戳

        tmpfile():创建并打开(w+b)一个新的临时文件

        walk():目录生成器

In [49]: g1=os.walk('/tmp')

In [50]: g1.
g1.close       g1.gi_frame    g1.next        g1.throw       
g1.gi_code     g1.gi_running  g1.send        

In [50]: g1.next
Out[50]: <method-wrapper 'next' of generator object at 0x24f0050>

In [51]: g1.next()
Out[51]: 
('/tmp',
 ['x', 'test1', 'vmware-root', 'test', '.ICE-unix'],
 ['test2',
  'yum_save_tx-2016-09-02-17-11cyWWR1.yumtx',
  'vgauthsvclog.txt.0',
  'passwd',
  'yum_save_tx-2016-09-21-23-45jB1DoO.yumtx'])

3、访问权限
     access():判断指定用户对文件是否有访问权限

    chmod():修改权限

     chown():改变属者,属组

     umask():设置默认权限模式

In [66]: os.a
os.abort   os.access  os.altsep  

In [66]: os.access('/root',0)
Out[66]: True

In [67]: os.access('/root',100)
Out[67]: False

4、文件描述符

     open():系统底层函数,打开文件

     read():

     write():


5、设备文件

     mkdev():根据主设备号,次设备号创建设备

     major():

      minor():


四、os.path模块   

os.path是os模块的的子模块 

实现路径管理,文件路径字符串本身的管理

In [5]: os.path
Out[5]: <module 'posixpath' from '/usr/local/python27/lib/python2.7/posixpath.pyc'>
In [3]: os.path.
os.path.abspath                     os.path.join
os.path.altsep                      os.path.lexists
os.path.basename                    os.path.normcase
os.path.commonprefix                os.path.normpath
os.path.curdir                      os.path.os
os.path.defpath                     os.path.pardir
os.path.devnull                     os.path.pathsep
os.path.dirname                     os.path.realpath
os.path.exists                      os.path.relpath
os.path.expanduser                  os.path.samefile
os.path.expandvars                  os.path.sameopenfile
os.path.extsep                      os.path.samestat
os.path.genericpath                 os.path.sep
os.path.getatime                    os.path.split
os.path.getctime                    os.path.splitdrive
os.path.getmtime                    os.path.splitext
os.path.getsize                     os.path.stat
os.path.isabs                       os.path.supports_unicode_filenames
os.path.isdir                       os.path.sys
os.path.isfile                      os.path.walk
os.path.islink                      os.path.warnings
os.path.ismount

1、跟文件路径相关

basename():去文件路径基名

dirname():去文件路径目录名

join():将字符串连接起来

split():返回dirname(),basename()元祖

splitext():返回(filename,extension 扩展名)元祖

In [6]: os.path.basename('/tmp/passwd')
Out[6]: 'passwd'

In [7]: os.path.dirname('/tmp/passwd')
Out[7]: '/tmp'

In [8]: os.listdir('/tmp')
Out[8]: 
['x',
 'test2',
 'yum_save_tx-2016-09-02-17-11cyWWR1.yumtx',
 'test1',
 'vmware-root',
 'vgauthsvclog.txt.0',
 'passwd',
 'test',
 '.ICE-unix',
 'yum_save_tx-2016-09-21-23-45jB1DoO.yumtx']

In [9]: for filename in os.listdir('/tmp'):print os.path.join("/tmp",filename)
/tmp/x
/tmp/test2
/tmp/yum_save_tx-2016-09-02-17-11cyWWR1.yumtx
/tmp/test1
/tmp/vmware-root
/tmp/vgauthsvclog.txt.0
/tmp/passwd
/tmp/test
/tmp/.ICE-unix
/tmp/yum_save_tx-2016-09-21-23-45jB1DoO.yumtx


In [24]: os.path.split('/etc/sysconfig/network')
Out[24]: ('/etc/sysconfig', 'network')

2、文件相关信息

getatime():返回文件最近访问时间

getctime()

getmtime()

getsize():返回文件的大小


3、查询

exists():判断指定文件是否存在

isabs():判断指定路径是否为绝对路径

isdir():是否为目录

isfile():是否存在而且文件

islink():是否存在且为链接

ismount():是否为挂载点

samefile():两个路径是否指向同一个文件


五、pickle模块

Python程序中实现文件读取或写出时,要使用转换工具把对象转换成字符串

实现对象持久存储

把对象存储在文件中:

       pickle模块:

        marshal:

把对象存储在DB中:

       DBM接口(需要装载第三方接口):


shelve模块:既然实现流式化也能存在DB中

In [31]: l1=[1,2,3,"4",'abc']

In [34]: f1=open('/tmp/test2','a+')

In [36]: s1="xj"

In [37]: f1.write(s1)

In [40]: cat /tmp/test2

In [42]: f1.close()

In [43]: cat /tmp/test2
xj

In [47]: print l1
[1, 2, 3, '4', 'abc']

In [57]: f1.write(l1)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-57-83ae8c8c88d4> in <module>()
----> 1 f1.write(l1)

TypeError: expected a character buffer object      #期望字符缓存对象

pickle模块:

In [58]: import pickle

In [61]: help(pickle.dump)

Help on function dump in module pickle:

dump(obj, file, protocol=None)
(END) 


[root@Node3 tmp]# cat test2
hello

n [77]: pickle.dump(l1,f1)     #前面已经定义了l1和f1,f1要是已打开的文件

In [78]: f1.flush()

[root@Node3 tmp]# cat test2
hello                          
(lp0
I1
aI2
aI3
aS'4'
p1
aS'abc'
p2

In [105]: l2=pickle.load(f2)

In [106]: l2
Out[106]: [1, 2, 3, '4', 'abc']


六、Python中的正则表达式

   文件是可迭代对象,以行为单位迭代

正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。

Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。

re 模块使 Python 语言拥有全部的正则表达式功能。

compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。

re 模块也提供了与这些方法功能完全一致的函数,这些函数使用一个模式字符串做为它们的第一个参数。


1、python中正则表达式的元字符

和bash中扩展正则表达式一样:

.,[],[^],  

        中括号用于指向一个字符集合比如[a-z],[a,b,c]

        中括号中可以使用元字符

        中括号中元字符.仅代表字面量

[0-9],\d(任意数字),\D(任意非数字)

[0-9a-zA-Z],\w,\W   

\s:任意空白字符:[\n\t\f\v\r],\S

?,+,{m},{m,n},{0,n},{m,}

^,$,\b,

|,(),\nn

(*|+|?|{})?:默认贪婪模式,在表示重复的元字符后面加个?非贪婪模式


捕获|分组

位置捕获:(...)

命名捕获:(?P<name>...)  #python所特有的


断言

      在目标字符串当前匹配位置的前面或后面进行的一种测试,但不占用字符

前向断言(?=...)      肯定    (?!...)  否定

后向断言(?<=...)    肯定    (?<!)  否定     

     ?是前向,?<是后向

 ?=是肯定 , ?! 是否定


2、re模块常用的方法

re.math():返回match对象

      属性:

               string

                re

                pos

                endpos

       方法:

               group() :分组,返回字符串

               groups():分组,返回以括号内的内容组成的元祖

               start()

               end()

re.search():第一次匹配到的字符,返回match对象

re.findall():匹配到的所有字符,返回一个列表

re.finditer():匹配到的所有字符,返回一个迭代器,内容是math对象

re.split(“m”,str):以m为分隔符,分割str,返回列表

re.sub():替换,返回字符串

re.subn():返回元祖

flags:

       I或IGNORECASE:忽略大小写

       M或MULTILINE:实现跨行匹配   #用的不多

        A或ASCII:仅执行8位ASCII码匹配

        U或UNICODE:

In [251]: import re

In [252]: re.
re.DEBUG        re.S            re.compile      re.search
re.DOTALL       re.Scanner      re.copy_reg     re.split
re.I            re.T            re.error        re.sre_compile
re.IGNORECASE   re.TEMPLATE     re.escape       re.sre_parse
re.L            re.U            re.findall      re.sub
re.LOCALE       re.UNICODE      re.finditer     re.subn
re.M            re.VERBOSE      re.match        re.sys
re.MULTILINE    re.X            re.purge        re.template


In [262]: re.match('a','abc')
Out[262]: <_sre.SRE_Match at 0x319b3d8>       #返回一个match对象

In [263]: match=re.match('a',"abc")

In [264]: match.         #match对象内部的相关属性或方法
match.end        match.groupdict  match.pos        match.start
match.endpos     match.groups     match.re         match.string
match.expand     match.lastgroup  match.regs       
match.group      match.lastindex  match.span     


In [264]: match.string     #匹配的字符串本身
Out[264]: 'abc'

In [266]: match.re
Out[266]: re.compile(r'a')    #匹配使用的文本,匹配时会自动编译

In [268]: match.group()     #greoup是一个方法,匹配到的字符串
Out[268]: 'a'

In [269]: match=re.match('a.',"abc")

In [270]: match.group()
Out[270]: 'ab'

In [271]: match.groups()   #以元祖方式返回所有匹配到的结果
Out[271]: ()



In [58]: str1="heelo world"

In [59]: re.search("(l(.))",str1)
Out[59]: <_sre.SRE_Match at 0x1603580>

In [60]: mat1=re.search("(l(.))",str1)

In [61]: mat1.
mat1.end        mat1.groupdict  mat1.pos        mat1.start
mat1.endpos     mat1.groups     mat1.re         mat1.string
mat1.expand     mat1.lastgroup  mat1.regs       
mat1.group      mat1.lastindex  mat1.span       

In [62]: help(mat1.group)


Help on built-in function group:

group(...)
    group([group1, ...]) -> str or tuple.
    Return subgroup(s) of the match by indices or names.
    For 0 returns the entire match.

In [63]: mat1.group()  #匹配到的全部字符串
Out[63]: 'lo'
    
In [66]: mat1.group(0)  #匹配到的全部字符串
Out[66]: 'lo'

In [67]: mat1.group(1)  #匹配到的第一个分组,不保护分组外的内容(括号外匹配到的内容)
Out[67]: 'lo'

In [68]: mat1.group(2)  #匹配到的第2个分组(第2个括号内的内容)
Out[68]: 'o'

In [69]: mat1.group(3)  #没有第三个
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-69-fe309512a255> in <module>()
----> 1 mat1.group(3)

IndexError: no such group


In [77]: mat1.groups()    #返回以匹配到分组为内容的元祖,不包括分组外的内容(括号外匹配到的内容)
Out[77]: ('lo', 'o')

In [78]: mat1.groups(0)
Out[78]: ('lo', 'o')

In [79]: mat1.groups(1)
Out[79]: ('lo', 'o')

In [80]: mat1.groups(2)
Out[80]: ('lo', 'o')

In [81]: mat1.groups(3)
Out[81]: ('lo', 'o')

In [89]: re.findall("(l(.))",str1)
Out[89]: [('lo', 'o'), ('ld', 'd')]

In [146]: for mat in re.findall("(o(.))",str1):print mat
('o ', ' ')
('or', 'r')

In [148]: for mat in re.finditer("(o(.))",str1):print mat
<_sre.SRE_Match object at 0x1603938>
<_sre.SRE_Match object at 0x16039c0>


In [150]: for mat in re.finditer("(o(.))",str1):print mat.group()
o 
or

In [151]: for mat in re.finditer("(o(.))",str1):print mat.groups()
('o ', ' ')
('or', 'r')





In [114]: str2               
Out[114]: 'hellO wOrld'

In [120]: mat2=re.findall("(l(o))",str2,re.I)    #忽略大小写

In [121]: mat2
Out[121]: [('lO', 'O')]

In [122]: mat2=re.findall("(l(o))",str2,)

In [123]: mat2
Out[123]: []


In [282]: match.start()   #从哪个位置开始匹配到
Out[282]: 0

In [283]: match.end()     #匹配结束的位置
Out[283]: 2

In [299]: match.pos     #从哪个位置开始搜索
Out[299]: 0

In [300]: match.endpos   #搜索的结束位置
Out[300]: 3


In [2]: url="www.magedu.com"

In [3]: re.search("m",url)
Out[3]: <_sre.SRE_Match at 0x14f7098>

In [5]: mat=re.search("m",url)

In [6]: mat
Out[6]: <_sre.SRE_Match at 0x14f7100>

In [7]: mat.
mat.end        mat.group      mat.lastgroup  mat.re         mat.start
mat.endpos     mat.groupdict  mat.lastindex  mat.regs       mat.string
mat.expand     mat.groups     mat.pos        mat.span       

In [8]: mat.group()
Out[8]: 'm'


In [10]: re.findall("m",url)
Out[10]: ['m', 'm']

In [11]: re.finditer("m",url)
Out[11]: <callable-iterator at 0x162f510>

In [12]: mat1=re.fi
re.findall   re.finditer  

In [12]: mat1=re.finditer("m",url)

In [13]: mat1.next()
Out[13]: <_sre.SRE_Match at 0x1626e68>

In [14]: mat1.next()
Out[14]: <_sre.SRE_Match at 0x1626ed0>

In [15]: mat1.next()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-15-e0f232c7f87c> in <module>()
----> 1 mat1.next()

StopIteration: 


In [19]: re.split(".",url)    #需要转义
Out[19]: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

In [20]: re.split("\.",url)
Out[20]: ['www', 'magedu', 'com']

In [30]: f1=open("/tmp/passwd","r+")

In [31]: re.split(":",f1.readline())
Out[31]: ['root', 'x', '0', '0', 'root', '/root', '/bin/bash\n']

re.sub():

In [34]: help(re.sub)


Help on function sub in module re:

sub(pattern, repl, string, count=0, flags=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the match object and must return
    a replacement string to be used.


In [35]: url
Out[36]: 'www.magedu.com'

In [37]: re.sub("ma","MA",url)
Out[38]: 'www.MAgedu.com'

In [35]: re.sub("m","M",url)
Out[35]: 'www.Magedu.coM'

In [36]: re.sub("m","M",url,1)
Out[36]: 'www.Magedu.com'

In [37]: re.sub("m","M",url,2)
Out[37]: 'www.Magedu.coM'

In [39]: re.subn("m","M",url,3)    #会显示替换了几次
Out[39]: ('www.Magedu.coM', 2)

In [169]: re.sub("M","S",url,count=2,flags=re.I)
Out[169]: 'www.Sagedu.coS'

In [170]: re.sub("M","S",url,count=2)
Out[170]: 'www.magedu.com'

re.match与re.search的区别

re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。

实例:

#!/usr/bin/pythonimport re

line = "Cats are smarter than dogs";matchObj = re.match( r'dogs', line, re.M|re.I)if matchObj: #加一个r表示是自然字符串不会被转义,例如\n在raw string中,是两个字符,\和n,而不会转意为换行符。由于正则表达式和\会有冲突,因此,当一个字符串使用了正则表达式后,最好在前面加上r
   print "match --> matchObj.group() : ", matchObj.group()else:
   print "No match!!"matchObj = re.search( r'dogs', line, re.M|re.I)if matchObj:
   print "search --> matchObj.group() : ", matchObj.group()else:
   print "No match!!"

以上实例运行结果如下:

No match!!search --> matchObj.group() :  dogs

检索和替换

Python 的re模块提供了re.sub用于替换字符串中的匹配项。

语法:

re.sub(pattern, repl, string, max=0)

返回的字符串是在字符串中用 RE 最左边不重复的匹配来替换。如果模式没有发现,字符将被没有改变地返回。

可选参数 count 是模式匹配后替换的最大次数;count 必须是非负整数。缺省值是 0 表示替换所有的匹配。

实例:

#!/usr/bin/pythonimport re

phone = "2004-959-559 # This is Phone Number"# Delete Python-style commentsnum = re.sub(r'#.*$', "", phone)print "Phone Num : ", num# Remove anything other than digitsnum = re.sub(r'\D', "", phone)    print "Phone Num : ", num

以上实例执行结果如下:

Phone Num :  2004-959-559Phone Num :  2004959559


正则表达式修饰符 - 可选标志

正则表达式可以包含一些可选标志修饰符来控制匹配的模式。修饰符被指定为一个可选的标志。多个标志可以通过按位 OR(|) 它们来指定。如 re.I | re.M 被设置成 I 和 M 标志:

修饰符描述
re.I使匹配对大小写不敏感
re.L做本地化识别(locale-aware)匹配
re.M多行匹配,影响 ^ 和 $
re.S使 . 匹配包括换行在内的所有字符
re.U根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.
re.X该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。