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)
 

 

posted @ 2019-06-25 21:08  ch_musk  阅读(115)  评论(0编辑  收藏  举报