#打开文件 file_object = open('info.txt', mode="rb") #读取文件内容,保存到变量 data = file_object.read() #关闭文件 file_object.close() data = data.decode("utf-8") print(data)
读取文件步骤:
注意:操作完的文件一定记得关闭
png = open('./1.png', mode="rb") data = png.read() png.close() print(data)
import os file_path = "./1.png" exists = os.path.exists(file_path) if exists: file_obj = open('./1.png', mode = 'rb') data = file_obj.read() file_obj.close() print(data) else: print('文件不存在')
file_obj = open('info.txt', mode='wb') file_obj.write("你好".encode("utf-8")) file_obj.close()
file_object = open("t1.txt", mode='wt', encoding='utf-8') #必须指定编码 file_object.write("武沛齐") file_object.close()
file_obj = open('./1.png', mode="rb") content = file_obj.read() file_obj.close() file_obj = open('./2.png', mode='wb') file_obj.write(content) file_obj.close()