python中文件的读写(day12下)
'''文本文件:(用字节表示。utf—8中,一个汉字为三个字节)
写多少,大小就是多少
比如py、 txt、 和 html格式
非文本文件
比如:avi jpg doc....
'''
![](https://img.haomeiwen.com/i6855378/c4260d7c245e5e66.png)
r,w,a:
操作的都是字符
目标文件:文本文件
字符 = 字节+解码
rb,wb,ab:
操作的都是字节
目标文件:任何文件
#文件默认格式为GBK,即ANSI格式
#当所在文档为utf-8格式时,需在open里加入(encoding='utf-8')
![](https://img.haomeiwen.com/i6855378/30119d58b2015da4.png)
01—read
file = open('haha.txt','r',encoding='utf-8')
content = file.read()
print(content)
file.close()
在python中运行需要转化路径
即加入cd desktop
在调用该函数所在地址运行该程序
![](https://img.haomeiwen.com/i6855378/5fc0055e1452f891.png)
02—write
'''
write模式中
如果文件名存在,则清空该内容,再重新写入
如果该文件不存在,则创建新的文件,再写入
光标在最后一个
'''
file = open('我想写点什么.txt','w')
file.write('写点这就行了')
file.write('hehe')
file.close()
![](https://img.haomeiwen.com/i6855378/c624b01477e70fce.png)
3—append追加写入
'''
a:追加写
接着原来的内容写
'''
file = open('爱写啥写啥.txt','a')
file.write('也许,是该到了放手的时候')
file.close()
![](https://img.haomeiwen.com/i6855378/dd01a6585c43f274.png)
4—rb,wb,ab
file = open('haha.txt','rb')
content = file.read()
print(type(content))
print(content)
print(content.decode('utf-8'))
file.close()
![](https://img.haomeiwen.com/i6855378/e8e0a97e4f1e9006.png)
file = open('haha.txt','wb')
info = '李白'
info = info.encode('utf-8')
file.write(info)
file.close()
![](https://img.haomeiwen.com/i6855378/a485684eaa04e9cd.png)