python 5-1 如何读写文本文件str1.encode('utf8')/decode('utf8')/open("text2.txt","wt",encoding="utf8")

python 5-1 如何读写文本文件
python2.x 写入文件前对unicode编码,读入文件后对二进制字符串编码

python3.x open函数指定’t’的文本模式,encoding指定编码格式

python2.x 写入文件前对unicode编码,读入文件后对二进制字符串编码

默认是通过unicode编码写进文件,通过unicode解码读出文件可以
可以通过str1.encode(“utf8”)和str1.decode(“utf8”)解开文件


>>> str1=u"你好"
>>> str1
u'\u4f60\u597d'
>>> str1.encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'

>>> print '\xe4\xbd\xa0\xe5\xa5\xbd'.decode('utf8')
你好
>>>
>>>



str1=u"你好,我爱中国"

f=open("xx.txt",'w')
f.write(str1.encode('utf8'))
f.close()
f=open("xx.txt",'r')
t=f.read()
print t.decode('utf8')  ==>你好,我爱中国

python2.x help(open)

>>> help(open)
Help on built-in function open in module __builtin__:

open(...)
    open(name[, mode[, buffering]]) -> file object

    Open a file using the file() type, returns a file object.  This is the
    preferred way to open a file.  See file.__doc__ for further information.

>>> 

python3.x open函数指定’t’的文本模式,encoding指定编码格式


>>> f = open("text2.txt","wt",encoding="utf8")
>>> f.write("hello,world")
11
>>> f.close()
>>> fr = open("text2.txt","rt",encoding="utf8")
>>> print(fr.read())
hello,world
>>> 

>>> 

python3.x help(open)


>>> help(open)
Help on built-in function open in module io:

open(...)
    open(file, mode='r', buffering=-1, encoding=None,
         errors=None, newline=None, closefd=True, opener=None) -> file object

    Open file and return a stream.  Raise IOError upon failure.

    file is either a text or byte string giving the name (and the path
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值