06 文件处理

''''''
'''
文件处理:
    open()
    
    写文件
        wt:写文本
        
    读文件
        rt:读文本
        
    追加写文件
        at:追加文本
        
注意:必须指定字符编码,以什么方式写
        就得以什么方式打开
        
执行python代码的过程:
    1、先启动python解释器
    2、把写好的python文件加载到解释器中
    3、检测python语法,执行代码
    
打开文件会产生两种资源:
    1、python程序
    2、操作系统打开文件
'''


#参数一:文件的绝对路径
#参数二:文件的模式
#参数三:encoding  指定的字符编码

#写文本文件
f = open('file.txt',mode='wt',encoding='utf-8')
f.write('tank') #产生file.txt文本,内容为tank
#关闭操作系统文件资源
f.close()


#读文本文件  r==rt
f = open('file.txt','r',encoding='utf-8')
print(f.read())
f.close()


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


'''
文件处理之上下文管理
    with open() as f    "句柄"
'''
#写文本文件
with open('file.txt','w',encoding='utf-8') as f:
    f.write('墨菲定律')

#读文本文件
with open('file.txt','r',encoding='utf-8') as f:
    res = f.read()
    print(res)

#追加写文本文件
with open('file.txt','a',encoding='utf-8') as f:
    f.write('
 围城')


'''
对图片、音频、视频读写
    rb模式,读取二进制,不需要指定字符编码
'''
#读取相片xb.jpg
with open('xb.jpg','rb') as f:
    res = f.read()
    print(res)
#
jpg = res
#
# #把xb.jpg的二进制流写入xb_copy.jpg文件中
with open ('xb_copy.jpg','wb') as f_w:
    f_w.write(jpg)

'''
with    管理多个文件
'''
#通过with来管理open打开的两个文件句柄f_r,f_w
with open('xb.jpg','rb') as f_r,open('xb_copy.jpg','wb') as f_w:
    #通过f_r句柄把图片的二进制流读取出来
     res = f_r.read()
    #通过f_W句柄把图片的二进制流写入xb_copy.jpg文件中
     f_w.write(res)
原文地址:https://www.cnblogs.com/urassya/p/11083582.html