python实训day01
本地文件读写
(1)读写纯文本文件
(2)读写非纯文本文件
(3)文本编码
(4)读写图片二进制
(5)Base64编码。
核心代码
1.读写纯文本文件:# 相路径同级./ 父级…/
绝对路径 所有电脑路径
file = open(’./chinese_utf-8.txt’,mode=‘r’,encoding=‘utf-8’)
content = file.read()
print(content)
file.close()
#chinese_utf-8.txt为外部文件
2.编码解码:print(‘中’.encode(encoding=‘gbk’))
3.读写非纯文本文件:with open(’./test1.jpg’,mode=‘r+b’) as f:
print(f.read())
4.Base64:import base64
str1 = ‘1234567891’
content_b64_bytes=base64.b64encode(str1.encode(encoding=‘utf-8’))
print(content_b64_bytes)
content_b64_str=content_b64_bytes.decode(encoding=‘ascii’)
print(’:’,content_b64_str)
#图片
with open(’./test1.jpg’,mode=‘rb’) as f:
content_bytes=f.read()
content_b64_bytes=base64.b64encode(content_bytes)
content_b64_str=content_b64_bytes.decode(encoding=‘ascii’)
print(content_b64_str)