我在Cygwin / Windows和通过ssh进入Debian ditro时遇到同样的问题。如果我打开一个终端,并立即复制/粘贴整个代码:
f = open('dst.txt', 'w', encoding='utf-8')
f.write('\xc4\xc4\xc4')
f.close
text = open('dst.txt', encoding='utf-8').read()
text
len(text)
我明白了:
Python 3.6.0a0 (default, Jul 7 2015, 23:55:18)
[GCC 4.7.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('dst.txt', 'w', encoding='utf-8')
>>> f.write('\xc4\xc4\xc4')
3
>>> f.close
<built-in method close of _io.TextIOWrapper object at 0x7f65c03b8b40>
>>> text = open('dst.txt', encoding='utf-8').read()
>>> text
''
>>> len(text)
0
>>>
现在,如果我在两个步骤中执行此操作:
f = open('dst.txt', 'w', encoding='utf-8')
f.write('\xc4\xc4\xc4')
f.close
然后:
text = open('dst.txt', encoding='utf-8').read()
text
len(text)
我明白了:
xx@xx:~$ python3
Python 3.6.0a0 (default, Jul 7 2015, 23:55:18)
[GCC 4.7.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('dst.txt', 'w', encoding='utf-8')
>>> f.write('\xc4\xc4\xc4')
3
>>> f.close
<built-in method close of _io.TextIOWrapper object at 0x7fb1a9353b40>
>>>
xx@xx:~$ python3
Python 3.6.0a0 (default, Jul 7 2015, 23:55:18)
[GCC 4.7.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> text = open('dst.txt', encoding='utf-8').read()
>>> text
'ÄÄÄ'
>>> len(text)
3
>>>
这里发生了什么?
答案 0 :(得分:1)
你没有调用close方法,你刚刚引用它 - 注意shell打印方法是什么,而不是它的结果(也就是None)。因此,当您尝试读取该文件时,该文件仍处于打开状态。显然,当您退出解释器时,文件将被关闭。
第三行应该是:
f.close()
答案 1 :(得分:0)
您忘记实际调用该方法,因此内容没有机会变得可读。
f.close()