Python入门day12——文件操作的补充

文件处理(其他操作)

控制文件操作的模式
  • x模式
    # x, 只写模式【不可读;不存在则创建,存在则报错】
    
    with open('a.txt',mode='x',encoding='utf-8') as f:
        pass # a.txt文件存在则报错,不存在则创建一个"a.txt"文件,不做操作
    
    with open('c.txt',mode='x',encoding='utf-8') as f:
        f.read() # 对"c.txt"文件不能进行读操作 报错
    
    with open('d.txt',mode='x',encoding='utf-8') as f:
        f.write('哈哈哈
    ') # "d.txt"中内容被写入内容 哈哈哈
    
    
  • b模式
    # 控制文件读写内容的模式
    x:只写模式
    t:文本模式
        1、读写都是以字符串(unicode)为单位
        2、只能针对文本文件
        3、必须指定字符编码,即必须指定encoding参数
    b:binary模式
        1、读写都是以bytes为单位
        2、可以针对所有文件
        3、一定不能指定字符编码,即一定不能指定encoding参数
    
    # 总结:
    # 1、在操作纯文本文件方面t模式帮我们省去了编码与解码的环节,b模式则需要手动编码与解码,所以此时t模式更为方便
    # 2、针对非文本文件(如图片、视频、音频等)只能使用b模式
    
    # 错误演示:t模式只能读文本文件
    with open(r'爱nmlgb的爱情.mp4',mode='rt') as f:
        f.read() # 硬盘的二进制读入内存-》t模式会将读入内存的内容进行decode解码操作 但是不是文本解码就会报错
    
    with open(r'test.jpg',mode='rb',encoding='utf-8') as f:
        res=f.read() # 硬盘的二进制读入内存—>b模式下,不做任何转换,直接读入内存
        print(res) # bytes类型—》当成二进制
        print(type(res)) # ValueError: binary mode doesn't take an encoding argument
    
    with open(r'd.txt',mode='rb') as f:
        res=f.read() # utf-8的二进制
        print(res,type(res)) # 
    
        print(res.decode('utf-8'))
    
    with open(r'd.txt',mode='rt',encoding='utf-8') as f:
        res=f.read() # utf-8的二进制->unicode b'xe5x93x88xe5x93x88xe5x93x88a' <class 'bytes'>
        print(res) # 哈哈哈a
    
    
    with open(r'e.txt',mode='wb') as f:
        f.write('你好hello'.encode('gbk')) # e.txt中写入'gbk'编码的'你好hello'
    
    with open(r'f.txt',mode='wb') as f:
        f.write('你好hello'.encode('utf-8')) # f.txt中写入'utf-8'编码的'你好hello'
        f.write('哈哈哈'.encode('gbk')) # 紧接着写入'gbk'编码的'你好hello'
    
    # 文件拷贝工具
    src_file=input('源文件路径>>: ').strip()
    dst_file=input('源文件路径>>: ').strip()
    with open(r'{}'.format(src_file),mode='rb') as f1,
        open(r'{}'.format(dst_file),mode='wb') as f2:
        # res=f1.read() # 内存占用过大
        # f2.write(res)
    
        for line in f1:
            f2.write(line)
    
    
    # 循环读取文件
    # 方式一:自己控制每次读取的数据的数据量
    with open(r'test.jpg',mode='rb') as f:
        while True:
            res=f.read(1024) # 1024
            if len(res) == 0:
                break
            print(len(res))
    
    
    # 方式二:以行为单位读,当一行内容过长时会导致一次性读入内容的数据量过大
    with open(r'g.txt',mode='rt',encoding='utf-8') as f:
        for line in f:
            print(len(line),line)
    
    with open(r'g.txt',mode='rb') as f:
        for line in f:
            print(line)
    
    with open(r'test.jpg',mode='rb') as f:
        for line in f:
            print(line)
    
文件操作的其他方法
  • 读相关操作
    # 1、readline:一次读一行
    with open(r'g.txt',mode='rt',encoding='utf-8') as f:
        # res1=f.readline()
        # res2=f.readline()
        # print(res2)
    
        while True:
            line=f.readline()
            if len(line) == 0:
                break
            print(line)
    
    # 2、readlines:
    with open(r'g.txt',mode='rt',encoding='utf-8') as f:
        res=f.readlines()
        print(res)
    
    # 强调:
    # f.read()与f.readlines()都是将内容一次性读入内存,如果内容过大会导致内存溢出,若还想将内容全读入内存,
    
  • 写相关操作
    # f.writelines():用于向文件中写入一序列的字符串。这一序列字符串可以是由迭代对象产生的,如一个字符串列表。换行需要制定换行符 
    。
    with open('h.txt',mode='wt',encoding='utf-8') as f:
        # f.write('1111
    222
    3333
    ')
    
        l=['11111
    ','2222','3333']
        # for line in l:
        #     f.write(line)
        f.writelines(l)
    
    # 结果
    11111
    22223333
    
    with open('h.txt', mode='wb') as f:
        l = [
            '1111aaa1
    '.encode('utf-8'),
            '222bb2'.encode('utf-8'),
            '33eee33'.encode('utf-8')
        ]
    	f.writelines(l)
    # 结果
    1111aaa1
    222bb233eee33
    # 补充1:如果是纯英文字符,可以直接加前缀b得到bytes类型
        l = [
            b'1111aaa1
    ',
            b'222bb2',
            b'33eee33'
        ]
    	f.writelines(l)
    # 结果
    1111aaa1
    222bb233eee33
    # 补充2:'上'.encode('utf-8') 等同于bytes('上',encoding='utf-8')
        l = [
            bytes('我',encoding='utf-8'),
            bytes('爱',encoding='utf-8'),
            bytes('中国',encoding='utf-8'),
        ]
        f.writelines(l)
    # 结果
    我爱中国
    
    # 3、flush:彻底完成输出并凊空缓冲中区,我们写入数据的时候,并不是直接操作的硬盘上的文件的,而是将获得的内容写到一个缓存区中,这样做是为了提高cpu的效率。在缓存区满了的情况下再写入到硬盘文件中去。而当缓冲区没有满的时候,必需将缓冲区的中内容写入到硬盘文件中去,就必须使用flush()将缓存区中的内容写到硬盘文件中,并将这个缓存区清空。
    with open('h.txt', mode='wt',encoding='utf-8') as f:
        f.write('哈')
        # f.flush()
    
    # 4、了解
    with open('h.txt', mode='wt',encoding='utf-8') as f:
        print(f.readable())
        print(f.writable())
        print(f.encoding)
        print(f.name)
    
    print(f.closed)
    
    # 结果
    False
    True
    utf-8
    h.txt
    True
    
文件的高级操作
  • 控制文件指针的移动
    指针移动的单位都是以bytes/字节为单位
    只有一种情况特殊:
          t模式下的read(n),n代表的是字符个数
    
    with open('aaa.txt',mode='rt',encoding='utf-8') as f:
        res=f.read(4)
        print(res)
    
    # f.seek(n,模式):n指的是移动的字节个数
    # 模式:
    # 模式0:参照物是文件开头位置
    f.seek(9,0)
    f.seek(3,0) # 3
    
    #模式1:参照物是当前指针所在位置
    f.seek(9,1)
    f.seek(3,1) # 12
    
    #模式2:参照物是文件末尾位置,应该倒着移动
    f.seek(-9,2) # 3
    f.seek(-3,2) # 9
    
    强调:只有0模式可以在t下使用,1、2必须在b模式下用
    
    # f.tell() # 获取文件指针当前位置
    # 示范
    with open('aaa.txt',mode='rb') as f:# aaa你好
        f.seek(9,0)
        f.seek(3,0) # 3
        # print(f.tell())
        #f.seek(4,0) # 报错
        res=f.read() 
        print(res.decode('utf-8'))
    
    with open('aaa.txt',mode='rb') as f:# aaa你好
        f.seek(9,1)
        f.seek(3,1) # 12
        print(f.tell()) # 12
    
    with open('aaa.txt',mode='rb') as f:# aaa你好
        f.seek(-9,2)
        # print(f.tell()) # 0
        f.seek(-3,2)
        # print(f.tell()) # 6
        print(f.read().decode('utf-8')) # 好
    ##### f.seek的应用
    
    
import time

with open('access.log', mode='rb') as f:
    # 1、将指针跳到文件末尾
    # f.read() # 错误
    f.seek(0,2)

    while True:
        line=f.readline()
        if len(line) == 0:
            time.sleep(0.3)
        else:
            print(line.decode('utf-8'),end='')
```
原文地址:https://www.cnblogs.com/yding/p/12506145.html