求助大佬,这个python作业的代码要怎么写?

2025-05-14 17:42:06
推荐回答(4个)
回答1:

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()

效果图

回答2:

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() # 关闭文件

回答3:

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())

回答4:

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())

   ...: