• python文件处理


     一:文件处理:

    open()

    写文件

           wt:写文本

     读文件

            rt:读文本

    追加写文件

            at:追加文本

    注意:必须指定字符编码
    以什么方式写,就必须用什么方式打开
    执行python代码的过程:
    1.先启动python解释器,加载到内存中
    2.把写好的python文件加载到解释器中
    3.检测python语法,执行代码

    打开文件会产生两种资源:
    1.python程序
    2.操作系统打开文件

    二:写文件
    参数1:文件的绝对路径
    参数2;mode操作文件的模式
    参数3:encoding,指定字符编码
    f=open('file.txt',mode='wt',encoding='utf-8')
    f.write('tank')
    f.close()    #关闭操作系统文件资源
     

    追加写文本文件
    f=open('file.txt','a',encoding='utf-8')
    a.write('合肥学院')
    a.close()

     三:文件处理之上下文管理
    #with可以管理open打开的文件
    会在with执行完毕后自动调用close()关闭文件with open()  

    with open() as f "句柄"
    #读
    with open('file.txt','r',encoding='utf-8') as f:
        res=f.read()
        print(res)
    #写
    with open('file.txt','w',encoding='utf-8') as f:
        f.write('墨菲定律')
    #追加
    with open('file.txt','a',encoding='utf-8') as f:
        f.write('围城')
        #f.close()    

    四:对图片音频视频读写
    rb模式,读取二进制,不需要指定字符编码
    with open('cxk.jpg','rb')as f:
        res=f.read()
        print(res)
    jpg=res

    #把cxk.jpg的二进制流写入cxk_copy.jpg文件中
    with open('cxk_copy.jpg','wb') as f_w
        f_w.write(jpg)

    五:with管理多个文件
    #通过with来管理open打开的两个文件句柄f_r,f_w
    with open('cxk.jpg','rb') as f_r,open('cxk_copy2.jpg','wb') as f_w:
        #通过f_r句柄把图片的二进制流读取出来
        res=f_r.read()
        #通过f_w句柄把图片的二进制写入cxk_copy.jpg文件中
        f_w.write(res)
     

  • 相关阅读:
    vue.js打包后,接口安全问题
    PHP开发api接口安全验证
    DOS命令操作 规格严格
    IIS 规格严格
    Swing语法高亮 规格严格
    Jetty 规格严格
    How to avoid “Illegal type in constant pool 规格严格
    数据库表产生类 规格严格
    利用Java编写简单IIS日志清理工具 规格严格
    语法高亮 规格严格
  • 原文地址:https://www.cnblogs.com/chmusk/p/12465879.html
Copyright © 2020-2023  润新知