zoukankan      html  css  js  c++  java
  • day12-文件高级及函数基本使用


    1.x模式(控制文件操作的模式)-》了解(只做了解没啥可说的。)
    x, 只写模式【不可读;不存在则创建,存在则报错】
    """
    with open('a.txt',mode='x',encoding='utf-8') as f:
    pass

    with open('c.txt',mode='x',encoding='utf-8') as f:
    f.read()

    with open('d.txt',mode='x',encoding='utf-8') as f:
    f.write('哈哈哈 ')


    2.b模式

    控制文件读写内容的模式
    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))

    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
    print(res)


    with open(r'e.txt',mode='wb') as f:
    f.write('你好hello'.encode('gbk'))

    with open(r'f.txt',mode='wb') as f:
    f.write('你好hello'.encode('utf-8'))
    f.write('哈哈哈'.encode('gbk'))


    文件拷贝工具

    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  这个是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)    # 这是b模式下的,上面是t模式
    
    with open(r'test.jpg',mode='rb') as f:
        for line in f:
            print(line)   # 读图片也是一样的
  • 相关阅读:
    Python for Data Science
    Python for Data Science
    Python for Data Science
    Python for Data Science
    Python for Data Science
    Python for Data Science
    Python for Data Science
    Python for Data Science
    Python for Data Science
    软件工程实践总结
  • 原文地址:https://www.cnblogs.com/xiao-zang/p/12504614.html
Copyright © 2011-2022 走看看