zoukankan      html  css  js  c++  java
  • Python入门篇-文件操作

                  Python入门篇-文件操作

                                          作者:尹正杰

    版权声明:原创作品,谢绝转载!否则将追究法律责任。

    一.文件IO常用操作

        open:打开
        read:读取
        write:写入
        close:关闭
        readline:行读取
        readlines:多行读取
        seek:文件指针操作
        tell:指针位置

    二.基本操作

    1>.打开操作

     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 """
     8 open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
     9     打开一个文件,返回一个文件(流对象)和文件描述符。打开文件失败,则返回异常。
    10 
    11 """
    12 
    13 f = open("passwd")        #file对象,默认以只读方式打开文件,该文件必须存在,否则会抛出"FileNotFoundError"异常
    14 print(f.read())           #d读取文件
    15 f.close()                 #关闭文件
    16 
    17 
    18 
    19 #"passwd"文件内容如下:
    20 root:x:0:0:root:/root:/bin/bash
    21 bin:x:1:1:bin:/bin:/sbin/nologin
    22 daemon:x:2:2:daemon:/sbin:/sbin/nologin
    23 adm:x:3:4:adm:/var/adm:/sbin/nologin
    24 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
    25 sync:x:5:0:sync:/sbin:/bin/sync
    26 shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
    27 halt:x:7:0:halt:/sbin:/sbin/halt
    28 mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
    29 operator:x:11:0:operator:/root:/sbin/nologin
    30 games:x:12:100:games:/usr/games:/sbin/nologin
    31 ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
    32 nobody:x:99:99:Nobody:/:/sbin/nologin
    33 systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
    34 dbus:x:81:81:System message bus:/:/sbin/nologin
    35 polkitd:x:999:998:User for polkitd:/:/sbin/nologin
    36 sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
    37 postfix:x:89:89::/var/spool/postfix:/sbin/nologin
    38 chrony:x:998:996::/var/lib/chrony:/sbin/nologin
    39 yinzhengjie:x:1000:1002:yinzhengjie:/home/yinzhengjie:/bin/bash
    40 apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
    41 tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
    42 zabbix:x:997:995:Zabbix Monitoring System:/var/lib/zabbix:/sbin/nologin
    43 mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash
    44 python:x:1001:1001::/home/python:/bin/bash

    2>.mode模式

    描述字符                              意义
      r 缺省的(即如果没有指定mode模式,则默认以只读方式打开),表示只读打开,如果使用write方法,会抛异常。如果文件不存在,抛出"FileNotFoundError"异常。   w 只写打开,如果文件不存在直接创建,如果文件已经存在,则清空文件内容,如果读取则抛出异常。   x 创建并写入一个新文件,文件不存在,创建文件,并只写方式打开。   a 写入打开,如果文件存在,则追加。文件存在,只写打开,追加内容,文件不存在,则创建后,只写打开,追加内容。   b 二进制模式,字节流,将文件就按照字节理解,与字符编码无关。二进制模式操作时,字节操作使用bytes类型。   t 缺省的文本模式。字符流,将文件的字节按照某种字符编码理解,按照字符操作,open的默认mode就是rt。   
    + 读写打开一个文件,给原来只读,只写方式打开提供缺省的读或者写能力。主要为r,w,a,x提供缺省的读写能力,但是文件获取依旧依照按照r,w,a,x字节的特征,+不能单独使用,可以任务它是为前面的模式字符做增强功能的。
    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    """
        文件操作中,最常用的操作就是读和写。
        文件访问的模式有两种:文本模式和二进制模式。不同模式下,操作函数不尽相同,表现的结果也不一样。
        打开或者要创建文件名。如果不指定路径,默认就是当前路径
    
    """
    
    f = open("passwd")            #file对象,默认以只读方式打开文件,该文件必须存在,否则会抛出"FileNotFoundError"异常
    print(f.readline())           #d读取文件
    f.close()                     #关闭文件
    
    
    print("*" * 20 + "我是分割线" + "*" * 20)
    
    f = open("passwd","r")
    f.write("abc")              #这里会抛异常"io.UnsupportedOperation: not writable",因为我们是以只读方式打开,但是我们这里要进行写操作是不被允许的!
    f.close()
    r模式打开文件
    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    
    
    f = open("a.txt","w")       #以只写的方式打开
    f.write("123")              #往打开的文件描述符写入内容为"123"
    f.close()                   #关闭文件
    
    
    f = open("a.txt","r")       #我们可以读出来写入的内容
    print(f.read())
    f.close()
    
    
    
    #以上代码执行结果如下:
    123
    w模式打开不存在的文件
    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    
    f = open("a.txt","r")       #我们可以读出来写入的内容
    print(f.read())
    f.close()
    
    print("*" * 20 + "我是分割线" +"*" *20)
    
    f = open("a.txt","w")       #以只写的方式打开,由于文件已经存在,我们再次打开它会将之前该文件的内容全部清空!
    f.write("666")              #我们往清空后的文件写入数据
    f.close()                   #关闭文件
    
    
    f = open("a.txt","r")       #我们可以读出来写入的内容
    print(f.read())
    f.close()
    
    
    
    #以上代码执行结果如下:
    123
    ********************我是分割线********************
    666
    w模式打开已经存在的文件

    三.文件指针,指向当前字节位置

    mode=r
      指针起始在于0
    mode
    =a
      指针起始在EOF
    tell()
      显示指针当前位置
    seek(offset[,whence])
      移动文件指针位置。offset偏移多少字符(即seek是按照自己偏移的)

    文本模式下
      whence 0
        缺省值,表示从头开始,offset只能正整数
      whence 1
        表示从当前位置,offset只接受0,相当于原地不动,没有什么用。
      whence 2 
        表示从EOF开始,offset只接受0,相当于移动文件指针到EOF。

    二进制模式下
      whence 0
        缺省值,表示从头开始,offset只能正整数
      whence 1
        表示当前位置,offset可正可负
      whence 2
        表示从EOF开始,offset可正可负
      二进制模式下支持任意起点的偏移,从头,从尾,从中间位置开始。向后seek可以超界,但是向前seek的时候,不能超界,否则抛异常。
    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    
    f = open("a.txt","r+")
    print("当前文件读取位置:{}".format(f.tell()))               #起始位置,因为我们还没有开始读取
    print("*" * 20 + "开始读取文件" + "*" * 20)
    print(f.read())                                              #我们将内容全部读取出来
    print("*" * 20 + "文件读取完毕" + "*" * 20)
    print("当前文件读取位置:{}".format(f.tell()))              #EOF,读取到文件末尾的指针位置
    f.seek(0)                                                   #回到起始位置
    print("当前文件读取位置:{}".format(f.tell()))              #查看当前文件指针位置
    f.close()
    
    
    
    #以上代码执行结果如下:
    当前文件读取位置:0
    ********************开始读取文件********************
    666
    ********************文件读取完毕********************
    当前文件读取位置:3
    当前文件读取位置:0
    文本方式打开
    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    
    f = open("a.txt","rb+")
    print("当前文件读取位置:{}".format(f.tell()))               #起始位置,因为我们还没有开始读取
    print("*" * 20 + "开始读取文件" + "*" * 20)
    print(f.read())                                              #我们将内容全部读取出来
    print("*" * 20 + "文件读取完毕" + "*" * 20)
    print("当前文件读取位置:{}".format(f.tell()))              #EOF,读取到文件末尾的指针位置
    f.write(b"abcdef")                                          #由于我们把之前的内容都读取出来啦,指针知道了文件末尾,此时我们在写入数据,其实在做追加写操作
    f.seek(0)                                                   #回到起始位置
    print("当前文件读取位置:{}".format(f.tell()))
    f.seek(2,1)                                                 #从当前指针开始,向后移动2个字符
    print("当前文件读取位置:{}".format(f.tell()))
    f.seek(2,2)                                                 #从EOF开始,向后移动2个字符
    print("当前文件读取位置:{}".format(f.tell()))
    f.seek(0)                                                   #回到起始位置
    print("当前文件读取位置:{}".format(f.tell()))
    f.seek(-2,2)                                                #从EOF开始,向前移动2个字符
    print("当前文件读取位置:{}".format(f.tell()))              #查看当前文件指针位置
    print("*" * 20 + "开始读取文件" + "*" * 20)
    print(f.read())                                              #我们将内容全部读取出来
    print("*" * 20 + "文件读取完毕" + "*" * 20)
    print("当前文件读取位置:{}".format(f.tell()))              #查看当前文件指针位置
    f.seek(-20,2)                                             #向前移动20个字符,但是如果向前移动的偏移量没有20个字符的话,就会抛出"OSError"异常
    f.close()
    
    
    
    #以上代码执行结果如下:
    当前文件读取位置:0
    ********************开始读取文件********************
    b'abcdefghijklmnopqrstuvwxyz'
    ********************文件读取完毕********************
    当前文件读取位置:26
    当前文件读取位置:0
    当前文件读取位置:2
    当前文件读取位置:34
    当前文件读取位置:0
    当前文件读取位置:30
    ********************开始读取文件********************
    b'ef'
    ********************文件读取完毕********************
    当前文件读取位置:32
    二进制方式打开

      

    四.buffering缓冲区

    buffering的分为4类
      buffering = -1
        -1表示使用缺省值大小的buffer。如果是二进制模式,使用io.DEFAULT_BUFFER_SIZE值,默认是4096或者8192。如果是文本模式,如果是终端设备,是行缓存方式,如果不是,则使用二进制模式的策略。
        文本模式(t)和二进制模式(b),都是io.DEFAULT_BUFFER_SIZE
      buffering = 0
        0只在二进制模式(b)使用,表示环比缓冲区(buffer).文本模式(t)不支持。
      buffering = 1
        1只在文本模式使用,表示使用行缓冲。意思就是见到换行符(t)就flush,但"io.DEFAULT_BUFFER_SIZE"依旧时缓冲上线。
      buffering > 1
        大于1用于指定buffer的大小。
        二进制模式(b)表示行缓冲大小。缓冲区的值可以超过io.DEFALUT_BUFFER_SIZE,直到设定的值超出后才把缓冲区flush。
        文本模式(t)表示io.DEFAULT_BUFFER_SIZE(即默认值大小),flush完后把当前字符串也写入磁盘。

    buffering看起来很麻烦,一般来说,只需要记得:
      1>.文本模式,一般都用默认缓冲区大小。
      2>.二进制模式,是一个个字节的操作,可以指定buiffer的大小
      3>.一般来说,默认缓冲区大小是个比较好的选择,除非明确知道,否则不调整它
      4>.一般编程中,明确知道需要写磁盘了,都会手动调用一次flush,而不是等到自动flush或者close的时候。

    buffer缓冲区
      缓冲区一个内存空间,一般来说是一个FIFO队列,到缓冲区满了或者达到阈值,数据才会flush到磁盘。
      flush()将缓冲区数据写入磁盘。
      clouse关闭前会调用flush()。
      io.DEFAULT_BUFFER_SIZE缺省缓冲区大小,字节。

    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    
    import io
    
    f = open("a.txt","w+b")
    print(io.DEFAULT_BUFFER_SIZE)
    
    f.write("https://www.cnblogs.com/yinzhengjie".encode())
    
    f.seek(0)
    
    f.write("www.baidu.com".encode())
    
    f.flush()
    
    f.close()
    
    
    f = open('a.txt',"w+b",4)
    f.write(b"yin")
    f.write(b"zhengjie")
    f.close()
    二进制模式
    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    import io
    
    
    f = open("a.txt","w",1)     #buffering=1,使用行缓冲
    
    f.write("yin")
    f.write("zhengjie" * 6)
    f.write("
    ")
    f.write("Hello
    Python")
    f.close()
    
    
    
    f = open("a.txt","w+",15)       #buffering>1使用指定大小的缓冲区
    f.write("yin")
    f.write("zhengjie")
    f.write("HELLO
    ")
    f.write("
    Python")
    f.write("a" * (io.DEFAULT_BUFFER_SIZE - 20))     #设置大于1没什么用
    f.write("https://www.cnblogs.com/yinzhengjie")
    f.close()
    文本模式
    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
     
     
    f = open("a.txt","wb+",0)       #buffering = 0这是一种特殊的二进制模式,不需要内存的buffer,可以看做是一个FIFO的文件。
    f.write(b"y")
    f.write(b"z")
    f.write(b"j")
    f.write(b"yinzhengjie" * 6)
    f.write(b"
    ")
    f.write(b"Hello
    Python")
    f.close()
    buffering=0案例

    五.编码(Encoding),仅文本模式使用

    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    
    """
        None表示使用缺省值编码,依赖操作系统,Windows,linux下测试代码如下所示。如果要显示指定的话我们可以用"encoding"关键词进行传参
        windows下缺省GBK(0xB0A1),Linux下缺省UTF-8(0xE5 95 8A)
    """
    
    f = open("a.txt","w")
    
    f.write("中国")
    
    f.close()

    六.errors

      什么样的编码错误将被捕获。
      None和strict表示有编码错误将抛出ValueError异常;ignore表示忽略。

    七.newline

    文本模式中,换行的转换。可以为None,空串,"
    ","
    ","
    "
      读时:
        None表示' ',' ',' '都被转换为' ';表示不会自动转换通过换行符;其他合法字符表示换行符就是指定字符,就会按照指定字符分行。
      写时:
        None表示' '都会被替换为系统缺省行分隔符os.linesep;' '或者''表示' '不替换,其他合法字符表示' '会被替换为指定的字符。
    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    
    f = open("a.txt","w")
    
    f.write("https://www.cnblogs.com/yinzhengjie
    Python
    https://www.cnblogs.com/yinzhengjie
    Python3.6")
    
    f.close()
    
    newlines = [None,'','
    ','
    ']
    for line  in newlines:
        f = open("a.txt",'r+',newline = line)   #缺省值替换所有的换行符
        print(f.readlines())
        f.close()
        
        
    
    #以上代码执行结果如下:
    ['https://www.cnblogs.com/yinzhengjie
    ', 'Python
    ', 'https://www.cnblogs.com/yinzhengjie
    ', '
    ', 'Python3.6']
    ['https://www.cnblogs.com/yinzhengjie
    ', 'Python
    ', 'https://www.cnblogs.com/yinzhengjie
    ', '
    ', 'Python3.6']
    ['https://www.cnblogs.com/yinzhengjie
    Python
    ', 'https://www.cnblogs.com/yinzhengjie
    
    ', 'Python3.6']
    ['https://www.cnblogs.com/yinzhengjie
    Python
    ', 'https://www.cnblogs.com/yinzhengjie
    
    ', 'Python3.6']
    newline案例

    八.closefd

    关闭文件描述符,True表示关闭它。False会在文件关闭后保持这个描述符。fileobj.fileno()查看。

    九.read

     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 """
     8 read(size=-1)
     9     size表示读取的多少个字符或字节;负数或者None表示读取到EOF
    10 """
    11 
    12 f = open("c.txt","r+",10)       #注意,我们传入的第三个参数不能为0,否则会报错"ValueError: can't have unbuffered text I/O"
    13 f.write("https://www.cnblogs.com/yinzhengjie")
    14 f.write("
    ")
    15 f.write("尹正杰到此一游!")
    16 f.seek(0)
    17 print(f.read(39))
    18 f.close()
    19 
    20 f = open("c.txt","rb+")
    21 print(f.read(39))           #注意这里读取的是字节,一个常见的汉字UTF-8字符编码一般对应的是3个字节
    22 print(f.read(1))
    23 f.close()
    24 
    25 
    26 
    27 
    28 #以上代码输出结果如下:
    29 https://www.cnblogs.com/yinzhengjie
    30 尹正杰
    31 b'https://www.cnblogs.com/yinzhengjie
    xd2xfc'
    32 b'xd5'

    十.行读取

     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 
     8 """
     9 readline(size = -1)
    10     一行行读取文件内容,size设置一次能够读取行内几个字符或字节。
    11 
    12 readlines(hint = -1)
    13     读取所有行的列表,指定hint则返回指定的行数。
    14 """
    15 
    16 
    17 f = open("a.txt")   #返回可迭代对象
    18 
    19 for line in f:
    20     print(line)
    21     
    22 f.close()

    十一.write

    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    
    """
    write(s)
        把字符串"s"写入到文件中并返回字符串的个数
    
    writelines(lines)
        将字符串列表写入文件。
    """
    
    
    f = open("a.txt","w+")
    
    lines = ['Jason',"2019
    ","Yinzhengjie"]
    
    f.writelines(lines)
    
    f.seek(0)
    
    print(f.read())
    
    f.close()
    
    
    
    #以上代码输出结果如下:
    Jason2019
    Yinzhengjie

    十二.close

    close:
      flush并关闭文件对象。   文件已经关闭,再次关闭没有任何小伙

    其他:
      seekable()是否可seek
      readable()是否可读
      writeable()是否可写
      closed是否已经关闭

    十三.上下文管理

    1>.问题的引出

    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    """
      我们可以使用lsof和ulimit查看所有的限制。其中open files就是打开文件数的限制,默认是1024.
      对于类似于文件对象的IO对象,一般来说都需要你不使用的时候关闭,注销,以释放资源。
      IO被打开的时候,会获得一个文件描述符。计算机资源是有限的,所以操作系统都会做限制。就是为了保护计算机的资源不要被完全耗尽,计算资源是共享的,不是独占的。
      一般情况下,除非特别明确的知道资源情况,否则不要提高资源的限制来解决问题。
    """"
    res
    = [] for _ in range(2000): #我们要循环2000次,但是在Linux你如果没有做调优的话,就会有"Too many open files"的相关报错 res.append(open("a.txt"))

    2>.解决方案一(异常处理)

     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 
     8 f = open("a.txt")
     9 
    10 try:
    11     f.write("Jason Yin")        #文件只读,写入失败
    12 finally:
    13     f.close()                   #使用finally可以保证打开的文件可以被关闭

    3>.解决方案二(上下文管理)

    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    
    """
    上下文管理:
        一种特殊的语法,交给解释器去释放文件。
        1>.使用with ... as关键字;
        2>.上下文管理的语句块并不会开启新的作用域;
        3>.with语句块执行完的时候,会自动关闭文件对象;
    """
    
    with open("a.txt","w") as f:
        f.write("Jason Yin")
    
    print(f.closed)     #测试f是否关闭
    
    
    f1 = open("b.txt","w")      
    
    with f1:       #很显然,处理上面的那种方式写文件,咱们还可以这样使用with语句哟~
        f1.write("2019")
    
    print(f1.closed)     #测试f是否关闭
    
    print("程序执行完毕")
    
    
    
    #试试代码执行结果如下:
    True
    True
    程序执行完毕

    十四.小试牛刀

    1>.指定一个源文件,实现copy到目标目录

    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    
    def copy(src,dest):
        with open(src) as f1:
            with open(dest,"w") as f2:
                f2.write(f1.read())
    
    
    filename1 = "a.txt"
    filename2 = "b.txt"
    
    
    f = open(filename1,"w+")
    lines = ["admin","jason","https://www.cnblogs.com/yinzhengjie"]
    f.writelines("
    ".join(lines))
    f.seek(0)
    print(f.read())
    f.close()
    
    
    copy(filename1,filename2)    
    
    
    
    #以上代码输出结果如下:
    admin
    jason
    https://www.cnblogs.com/yinzhengjie
    admin
    jason
    https://www.cnblogs.com/yinzhengjie
    执行上述脚本后a.txt文件内容
    admin
    jason
    https://www.cnblogs.com/yinzhengjie
    执行上述脚本后b.txt文件内容

    2>.有一个文件,对其进行单词统计,不区分大小写,并显示单词重复最多的10个单词。

    The Apache Hadoop software library is a framework that allows for the distributed processing of large data sets across clusters of computers using simple programming models. It is designed to scale up from single servers to thousands of machines, each offering local computation and storage. Rather than rely on hardware to deliver high-availability, the library itself is designed to detect and handle failures at the application layer, so delivering a highly-available service on top of a cluster of computers, each of which may be prone to failures.
    hadoop.txt
     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 d = {}
     8 
     9 with open("hadoop.txt",encoding="utf8") as f:
    10     for line in f:
    11         words = line.split()
    12         for word in map(str.lower,words):
    13             d[word] = d.get(word,0) + 1
    14 
    15 print(sorted(d.items(),key=lambda  item :item[1],reverse=True))
    16 
    17 
    18 
    19 #以上代码输出结果如下:
    20 [('of', 6), ('to', 5), ('the', 4), ('is', 3), ('a', 3), ('library', 2), ('designed', 2), ('each', 2), ('and', 2), ('on', 2), ('apache', 1), ('hadoop', 1), ('software', 1), ('framework', 1), ('that', 1), ('allows', 1), ('for', 1), ('distributed', 1), ('processing', 1), ('large', 1), ('data', 1), ('sets', 1), ('across', 1), ('clusters', 1), ('computers', 1), ('using', 1), ('simple', 1), ('programming', 1), ('models.', 1), ('it', 1), ('scale', 1), ('up', 1), ('from', 1), ('single', 1), ('servers', 1), ('thousands', 1), ('machines,', 1), ('offering', 1), ('local', 1), ('computation', 1), ('storage.', 1), ('rather', 1), ('than', 1), ('rely', 1), ('hardware', 1), ('deliver', 1), ('high-availability,', 1), ('itself', 1), ('detect', 1), ('handle', 1), ('failures', 1), ('at', 1), ('application', 1), ('layer,', 1), ('so', 1), ('delivering', 1), ('highly-available', 1), ('service', 1), ('top', 1), ('cluster', 1), ('computers,', 1), ('which', 1), ('may', 1), ('be', 1), ('prone', 1), ('failures.', 1)]
    解法一
     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 def makekey(s:str):
     8     chars = set(r"""!'''#./()[],*-""")
     9     key = s.lower()
    10     ret = []
    11     for i ,c in enumerate(key):
    12         if c in chars:
    13             ret.append(" ")
    14         else:
    15             ret.append(c)
    16     return "".join(ret).split()
    17 
    18 d = {}
    19 
    20 with open("hadoop.txt",encoding="utf8") as f:
    21     for line in f:
    22         words = line.split()
    23         for wordlist in map(makekey,words):
    24             for word in wordlist:
    25                 d[word] = d.get(word,0) + 1
    26 
    27 for k,v in sorted(d.items(),key=lambda  item:item[1],reverse=True):
    28     print(k,v)
    29     
    30     
    31     
    32 #以上代码输出结果如下:
    33 of 6
    34 to 5
    35 the 4
    36 is 3
    37 a 3
    38 library 2
    39 computers 2
    40 designed 2
    41 each 2
    42 and 2
    43 on 2
    44 failures 2
    45 apache 1
    46 hadoop 1
    47 software 1
    48 framework 1
    49 that 1
    50 allows 1
    51 for 1
    52 distributed 1
    53 processing 1
    54 large 1
    55 data 1
    56 sets 1
    57 across 1
    58 clusters 1
    59 using 1
    60 simple 1
    61 programming 1
    62 models 1
    63 it 1
    64 scale 1
    65 up 1
    66 from 1
    67 single 1
    68 servers 1
    69 thousands 1
    70 machines 1
    71 offering 1
    72 local 1
    73 computation 1
    74 storage 1
    75 rather 1
    76 than 1
    77 rely 1
    78 hardware 1
    79 deliver 1
    80 high 1
    81 availability 1
    82 itself 1
    83 detect 1
    84 handle 1
    85 at 1
    86 application 1
    87 layer 1
    88 so 1
    89 delivering 1
    90 highly 1
    91 available 1
    92 service 1
    93 top 1
    94 cluster 1
    95 which 1
    96 may 1
    97 be 1
    98 prone 1
    解法二
      1 #!/usr/bin/env python
      2 #_*_coding:utf-8_*_
      3 #@author :yinzhengjie
      4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
      5 #EMAIL:y1053419035@qq.com
      6 
      7 def makekey(s:str):
      8     chars = set(r"""!'''#./()[],*-""")
      9     key = s.lower()
     10     ret = []
     11     start = 0
     12     length = len(key)
     13 
     14     for i ,c in enumerate(key):
     15         if c in chars:
     16             if start == i:      #如果紧挨着还是特殊字符,start一定等于i
     17                 start += 1      #加1biangcontinue
     18                 continue
     19             ret.append(key[start:i])
     20             start = i + 1       #加1是跳过这个不需要的特殊字符c
     21     else:
     22         if start < len(key):    #小于,说明还有有效的字符,而且一直到末尾
     23             ret.append(key[start:])
     24     return ret
     25 
     26 
     27 # print(makekey("os.path.exists(path)"))
     28 
     29 d = {}
     30 
     31 with open("hadoop.txt",encoding="utf8") as f:
     32     for line in f:
     33         words = line.split()
     34         for wordlist in map(makekey,words):
     35             for word in wordlist:
     36                 d[word] = d.get(word,0) + 1
     37 
     38 for k,v in sorted(d.items(),key=lambda  item:item[1],reverse=True):
     39     print(k,v)
     40 
     41 
     42 
     43 #以上代码输出结果如下:
     44 of 6
     45 to 5
     46 the 4
     47 is 3
     48 a 3
     49 library 2
     50 computers 2
     51 designed 2
     52 each 2
     53 and 2
     54 on 2
     55 failures 2
     56 apache 1
     57 hadoop 1
     58 software 1
     59 framework 1
     60 that 1
     61 allows 1
     62 for 1
     63 distributed 1
     64 processing 1
     65 large 1
     66 data 1
     67 sets 1
     68 across 1
     69 clusters 1
     70 using 1
     71 simple 1
     72 programming 1
     73 models 1
     74 it 1
     75 scale 1
     76 up 1
     77 from 1
     78 single 1
     79 servers 1
     80 thousands 1
     81 machines 1
     82 offering 1
     83 local 1
     84 computation 1
     85 storage 1
     86 rather 1
     87 than 1
     88 rely 1
     89 hardware 1
     90 deliver 1
     91 high 1
     92 availability 1
     93 itself 1
     94 detect 1
     95 handle 1
     96 at 1
     97 application 1
     98 layer 1
     99 so 1
    100 delivering 1
    101 highly 1
    102 available 1
    103 service 1
    104 top 1
    105 cluster 1
    106 which 1
    107 may 1
    108 be 1
    109 prone 1
    解法三

     3>.实时监控一个文件内容

    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    import time
    
    MonitoringFile = "access.log"                       #定义我们需要监控的文件名称。
    
    with open(MonitoringFile,'r',encoding="utf-8") as f:
        f.seek(0,2)                         #表示将光标对应文件的末尾。
        while True:
            line = f.readline().strip()                #读取每行的内容,并把换行符脱掉。
            if line :
                print("新增了一条记录:",line)           #打印从文件末尾新增的每一行内容
            time.sleep(0.5)                             #每次打印一行信息都需要睡0.5秒钟。
  • 相关阅读:
    浅谈SQLite——查询处理及优化
    .NET 并行(多核)编程系列之七 共享数据问题和解决概述
    sql 存储过程学习一
    SQL中获得EXEC后面的sql语句或者存储过程的返回值的方法 【收藏】
    script刷新页面,刷新代码
    C#编程中关于数据缓存的经验总结
    SQL存储过程的概念,优点及语法
    SQLite数据库安装、试用及编程测试手记
    c# sqlite 数据库加密
    进销存管理系统的设计与实现
  • 原文地址:https://www.cnblogs.com/yinzhengjie/p/10977416.html
Copyright © 2011-2022 走看看