文件读写

Py2

In [1]: f = open('t1.txt', 'w')
In [2]: f.write('敛青'.encode('utf8'))
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-2-9d94e12b19c7> in <module>()
----> 1 f.write('敛青'.encode('utf8'))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
In [3]: f.write(u'敛青'.encode('utf8'))
In [4]: f.flush()
In [5]: f.close()
In [6]: f = open('t1.txt')
In [7]: s = f.read()
In [8]: print s.decode('utf8')
敛青

Py3

In [2]: f = open('t1.txt', 'wt', encoding='utf8')
In [3]: f.write('敛青')
Out[3]: 2
In [4]: f.flush()
In [5]: f.close()
In [6]: f = open('t1.txt', 'rt', encoding='utf8')
In [7]: s = f.read()
In [8]: print(s)
敛青

差别

  • py2 'abc' => py3 b'abc'
  • py2 u'abc' => py3 'abc'

results matching ""

    No results matching ""