读取一个文本文件
用 file 方法打开一个已有文本文件,mode选择只读 ‘r’
content 命名 以及打印,关闭 file 方法。
file = open('./English.txt',mode='r',encoding='utf-8')
content = file.read()
print(content)
file.close()
写本地文件
file = open('./3test.txt',mode='a',encoding='utf-8')
file.write('hello world 你好,世界')
file.close()
with语句
文件操作和其他操作,共性 开始前准备和收尾工作抽离自动完成,便于我们将主要精力放在逻辑上。
with open('./chinese.txt',mode='r',encoding='UTF8') as f:
content = f.read()
print(content)
图片操作(非文本)
读取本地非文本文件
with open('./iu.JPG',mode='r+b') as f:
print(f.read())
写非文本文件
img_content_bytes = (代码块······)
with open('./6iu.jpg',mode='w+b')as f:
f.write(img_content_bytes)
如图
base64 编码解码
import base64
str1 = '17612325939'
content_b64_bytes = base64.b64encode(str1.encode(encoding='utf-8'))
print('绿软是:',content_b64_bytes)
str1 = 'MTc2MTIzMjU5Mzk='
b64_bytes = str1.encode(encoding='ascii')
print(b64_bytes)
raw_bytes = base64.b64decode(b64_bytes)
print(raw_bytes)
raw_str = raw_bytes.decode(encoding='utf-8')
print(raw_str)
输出结果如下:
绿软是: b’MTc2MTIzMjU5Mzk=’
b’MTc2MTIzMjU5Mzk=’
b’17612325939’
17612325939