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