• 【python-文件的操作】


    # ### 文件操作
    """
    fp = open("文件名","模式","字符编码集")
    fp 文件的io对象 (文件句柄)
    i : input  输入
    o : output 输出
    """
     
    # 1.文件的写入操作
    # (1) 打开文件  (把冰箱门打开)
    '''r"E:python30ceshi1.txt" 可以指定路径'''
    fp = open("ceshi1.txt",mode="w",encoding="utf-8")
    # (2) 写入内容  (把大象塞进去)
    fp.write("把大象塞进去")
    # (3) 关闭文件  (把冰箱门关上)
    fp.close()
     
     
    # 2.文件的读取操作
    # (1) 打开文件
    fp = open("ceshi1.txt",mode="r",encoding="utf-8")
    # (2) 读取内容
    res = fp.read()
    print(res)
    # (3) 关闭文件
    fp.close()
     
     
    # 3.字节流的转换
    """
    二进制的字节流:用来传输或者存储的数据 bytes
    b"123" 要求: b开头的字符串 ,内容必须是ascii编码
     
    # 将字符串和字节流(Bytes流)类型进行转换 (参数写成转化的字符编码格式)
        #encode() 编码  将字符串转化为字节流(Bytes流)
        #decode() 解码  将Bytes流转化为字符串
    """
     
    strvar = "我爱你"
    # 将字符串转化为字节流
    res = strvar.encode("utf-8")
    print(res)
     
    # 将Bytes流转化为字符串
    strvar2 = res.decode("utf-8")
    print(strvar2)
     
    # len 算一下字节流的长度(一个字符是3个字节)
    num = len(res)
    print(num)
    res = b"xe7x88xb1".decode("utf-8")
    print(res)
    res = "我爱王二麻子,我永远是你得不到的男人"
    print(res.encode("utf-8"))
     
    # 4.存储字节流
    """wb 与 rb 来存储二进制字节流"""
    # 1.打开文件
    '''字节流模式下,无需指定编码集'''
    fp = open("ceshi2.txt",mode="wb")
    str_bytes = "我好想你,我的baby".encode("utf-8")
     
    # 2.写入字节流
    fp.write(str_bytes)
     
    # 3.关闭文件
    fp.close()
     
     
    # 5.读取字节流
    # 1.打开文件
    '''字节流模式下,无需指定编码集'''
    fp = open("ceshi2.txt",mode="rb")
    # 2.读取字节流
    res = fp.read()
    # 3.关闭文件
    fp.close()
     
    print(res)
    strvar = res.decode("utf-8")
    print(strvar)
     
    # 复制文件夹中 集合.png 这张图片
    """图片 音频 视频这样的文件都是二进制bytes"""
    # 1.先把所有的二进制字节流读取出来
    fp = open("集合.png",mode="rb")
    str_bytes = fp.read()
    fp.close()
     
    print(str_bytes)
     
    # 2.再把所有读出来的二进制字节流写入到另外一个文件中
    fp = open("集合2.png",mode="wb")
    fp.write(str_bytes)
    fp.close()
  • 相关阅读:
    es使用java的api操作
    vip视频解析保存
    springboot项目中常遇到的问题-初学者最容易犯的错
    spring中使用@value注入static静态变量
    Hardware assisted virtualization and data execution protection must be enabled in the BIOS. See https://docs.docker.com/docker-for-windows/troubleshoot/#virtualization
    rabbitmq的简单使用
    微信朋友圈点赞功能
    SQLServer删除重复数据保留一条
    公司企业的网站备案工信部短信验证失败怎么办?证件不是营业执照,而是身份证号
    全部常用邮件端口25、109、110、143、465、995、993、994
  • 原文地址:https://www.cnblogs.com/bonnyxinxin/p/13210275.html
Copyright © 2020-2023  润新知