23 文件的操作

#只读模式,文本,gb2312
f = open('d:老人与海.txt','r',encoding='gb2312')
content = f.read()
print(content)
f.close()

#只读模式 utf-8
f = open('老人与海','r',encoding='utf-8')
content = f.read()
print(content)
f.close()

#二进制只读模式
f = open('老人与海','rb')
# content = f.read()
# print(content)
# f.close()

#覆盖写模式
f = open('log','w',encoding='utf-8')
content = f.write('骑兵,步兵')
f.close()

#覆盖写模式
f = open('log','w',encoding='utf-8')
content = f.write('阿斯顿发射点阿瑟东f')
f.close()

#二进制覆盖写模式
f = open('log','wb')
content = f.write('阿斯顿发射点阿瑟东f'.encode('gbk'))
f.close()

#追加写模式
f = open('log','a',encoding='utf-8')
f.write("sa fasdfas")
f.close()

#二进制追加写模式
f = open('log','ab')
f.write("哎呦不错!!!!".encode('utf-8'))
f.close()
原文地址:https://www.cnblogs.com/wssaried/p/9895620.html