Python-文件的读写

所有文件分为2大类:文本文件和二进制文件   (图片 视频 音频 word ppt等都属于二进制文件)
读取文件用到的函数:open和close

open函数
fh1=open(r'文件路径和文件名','r') # r--read读取,fh1--文件句柄,通过文件句柄控制文件
date=fh1.read()
print(date)
fh1.close()#文件操作完毕后一定要关闭文件IO资源,只要用了open函数,就一定要用close。
例1:在电脑的这个位置 D:\003\004python学习 存放了文件 将进酒.txt
读取的方法为:
fh1=open(r"D:\003自制\004python学习\将进酒.txt","r")  #第一个r是取消转义,最后面的r是读取
date=fh1.read()
print(date)
fh1.close()
——————
例2:readline,按行读取 读取的是第一句
fh1=open(r"D:\003\004python学习\将进酒.txt","r")
date1=fh1.readline()
print(date1)
fh1.close()
——————
例3:readlines,按行读取所有,结果是list格式,没行用\n换行
fh1=open(r"D:\003\004python学习\将进酒.txt","r")
dates=fh1.readlines()
print(dates)
fh1.close()
——————
例4:从例3中变过来,例3的结果为list列表,如果想取其中的某一行则可以,如下取的则是括号的那一行。
fh1=open(r"D:\003\004python学习\将进酒.txt","r")
dates=fh1.readlines()
print(dates[2])
fh1.close()
——————
*写入用w--write    a--append
例4:如果文件名之前就有,那么就是把之前的内容替换下来。如果之前文件不存在,则是新建个文件,把内容写入。
fh=open(r"D:\003\004python学习\将进酒.txt","w") #w--write 
fh.write("hello world!")
fh.close()
————
相同效果的另一种写法
fh=open(r"D:\003\004python学习\将进酒.txt","w") #w--write 
date="hello world!"
fh.write(date)
fh.close()
————————
例5:保留之前的内,先在新写入的内连接在后面,如果需要换行,则只需在新写入的内容前面加上换行符\n
fh=open(r"D:\003\004python学习\将进酒.txt","a")  #a--append  附加
date="这就是我!"
fh.write(date)
fh.close()
————————
二进制文件的读写
例6:注意文件名的格式,读出的为二进制的文件
fh=open(r'D:\003\004python学习\01.png','rb')   #r--read   b--beyte
data=fh.read()  #读出该二进制文件
print(data)
fh.close()
——————
例7:在6的基础上,把读出的二进制文件复制到另外的文件夹中,或者复制后重新命名
fh=open(r'D:\003\004python学习\01.png','rb')   #r--read   b--beyt
data=fh.read()  #读出该二进制文件
fh1=open(r'D:\003\004python学习\666.png','wb') #注意文件名文件地址,w--write   b---byte
fh1.write(data)    #把句柄fh里面的内容写入句柄fh1中,即是复制
fh.close()  
fh1.close()   #最后记得一定要关掉
。。。。。。
posted @ 2020-05-19 10:13  因家三姑娘  阅读(175)  评论(0)    收藏  举报