python中文件的读写(day12下)

'''文本文件:(用字节表示。utf—8中,一个汉字为三个字节)

写多少,大小就是多少

比如py、  txt、 和 html格式

非文本文件

比如:avi  jpg  doc....

'''

python中文件的读写(day12下)_第1张图片
说明

r,w,a:

操作的都是字符

目标文件:文本文件

字符 = 字节+解码

rb,wb,ab:

操作的都是字节

目标文件:任何文件

#文件默认格式为GBK,即ANSI格式

#当所在文档为utf-8格式时,需在open里加入(encoding='utf-8')


python中文件的读写(day12下)_第2张图片
haha.txt

01—read

file = open('haha.txt','r',encoding='utf-8')

content = file.read()

print(content)

file.close()

在python中运行需要转化路径

即加入cd  desktop

在调用该函数所在地址运行该程序

python中文件的读写(day12下)_第3张图片
运行结果

02—write

'''

write模式中

如果文件名存在,则清空该内容,再重新写入

如果该文件不存在,则创建新的文件,再写入

光标在最后一个

'''

file = open('我想写点什么.txt','w')

file.write('写点这就行了')

file.write('hehe')

file.close()


python中文件的读写(day12下)_第4张图片
写入运行结果

3—append追加写入

'''

a:追加写

接着原来的内容写

'''

file = open('爱写啥写啥.txt','a')

file.write('也许,是该到了放手的时候')

file.close()

python中文件的读写(day12下)_第5张图片
append运行结果

4—rb,wb,ab

file = open('haha.txt','rb')

content = file.read()

print(type(content))

print(content)

print(content.decode('utf-8'))

file.close()

python中文件的读写(day12下)_第6张图片
rb只读运行结果

file = open('haha.txt','wb')

info = '李白'

info = info.encode('utf-8')

file.write(info)

file.close()

python中文件的读写(day12下)_第7张图片
wb写入运行结果

你可能感兴趣的:(python中文件的读写(day12下))