s = """Precious things are very few!
I wish you success in your work!
With the compliments of the season!
May joy and health be with you always!
A friend is a loving companion at all times!"""
with open('Exp030202.txt', 'wb')as f:
f.write(s.encode('UTF-8','strict'))
f.close()
with open('Exp030202.txt', 'rb')as f:
read_data = f.read()
print(read_data)
f.close()
效果图
f = open("test.txt", 'wb') # 二进制写模式
f.write(b'Precious things are very few!') # 二进制写
f.write(b'I wish you success in your work!') # 二进制写
f.write(b'With the compliments of the season!') # 二进制写
f.write(b'May joy and health be with you always!') # 二进制写
f.write(b'A friend is a loving companion at all times!') # 二进制写
f.close() # 关闭文件
f = open("test.txt", 'rb') # 二进制读
print(f.read()) # 打印读出来的数据
f.close() # 关闭文件
ss = '''Precious things are very few!
I wish you success in your work!
With the compliments of the season!
May joy and health be with you always!
A friend is a loving companion at all times!'''
with open('./Exp030202.txt','wb',encoding='utf-8') as file1:
file1.write(ss)
with open('./Exp030202.txt','rb',encoding='utf-8') as file2:
print(file2.read())
In [4]: with open(r'e:/Exp030202.txt','wb') as t:
...: t.write(ss.encode())
...:
...:
In [5]: with open(r'e:/Exp030202.txt','rb') as t:
...: print(t.read())
...: