标签:字符串类型 encode 操作 close open print type 哈哈 ...
哈哈哈.txt
1.文件路径:C:\Users\Administrator\Desktop\哈哈哈.txt
2.编码方式:utf-8、gbk。。。
3.操作方式:只读,只写,追加,读写,写读......
绝对路径下
f = open(‘d:\哈哈哈.txt‘,mode=‘r‘,encoding=‘gbk‘) context = f.read() print(context,type(context))#字符串类型 f.close()
相对路径下
f = open(‘哈哈哈‘,mode=‘r‘,encoding=‘utf-8‘) context = f.read() print(context,type(context))#字符串类型 f.close()
对于w:没有此文件就会创建,有文件则会将源文件的内容全部删除然后在写入内容
f = open(‘log‘,mode=‘w‘,encoding=‘utf-8‘) f.write(‘跳舞吧‘) f.close() f = open(‘log‘,mode=‘wb‘) f.write(‘跳舞‘.encode(‘utf-8‘))#写入的是byte类型,将其转换成utf-8类型 f.close()
f = open(‘log‘,mode=‘a‘,encoding=‘utf-8‘) f.write(‘跳舞了不起?‘)#写入的是byte类型,将其转换成utf-8类型 f.close() f = open(‘log‘,mode=‘ab‘) f.write(‘jhgfd‘.encode(‘utf-8‘))#写入的是byte类型,将其转换成utf-8类型 f.close()
f = open(‘log‘,mode=‘r+‘,encoding=‘utf-8‘) print(f.read()) f.write(‘夏夏,胖胖‘) f.close() f = open(‘log‘,mode=‘r+b‘) print(f.read())#结果:b‘‘ f.write(‘nice‘.encode(‘utf-8‘)) f.close()
f = open(‘log‘,mode=‘w+‘,encoding=‘utf-8‘) f.write(‘aaa‘) f.seek(0)#调光标之后可以输出,否则无法输出,write后默认在字符串最后 print(f.read())#结果:aaa f.close() f = open(‘log‘,mode=‘wb+‘) f.write(‘fds‘.encode(‘utf-8‘)) f.seek(0)#调光标之后可以输出,否则无法输出,write后默认在字符串最后 print(f.read())#结果:b‘fds‘ f.close()
f = open(‘log‘,mode=‘a+‘,encoding=‘utf-8‘) f.write(‘妈耶‘) f.seek(0)#调光标之后可以输出,否则无法输出,write后默认在字符串最后 print(f.read())#结果:妈耶 f.close() f = open(‘log‘,mode=‘a+b‘) f.write(‘妈耶‘.encode(‘utf-8‘)) f.seek(0)#调光标之后可以输出,否则无法输出,write后默认在字符串最后 print(f.read())#结果:妈耶 f.close()
标签:字符串类型 encode 操作 close open print type 哈哈 ...
原文地址:https://www.cnblogs.com/Cheryol/p/9706187.html