2015-10-12 15 views
0

我在Cygwin/Windows和通過ssh到Debian ditro中遇到同樣的問題。如果我打開一個終端,以及複製/一次粘貼整個代碼:Python3:複製/粘貼序列僅在兩步完成時才起作用

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 

Then:

text = open('dst.txt', encoding='utf-8').read() 
text 
len(text) 

我得到:

[email protected]:~$ 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> 
>>> 
[email protected]:~$ 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 
>>> 

這是怎麼回事?

回答

1

你還沒有調用close方法,你剛剛引用它 - 請注意,shell打印的是方法是什麼,而不是它的結果(這將是None)。因此,當您嘗試閱讀文件時,該文件仍然可以寫入。顯然,當你退出解釋器時,該文件被關閉。

第三行應該是:

f.close() 
0

你忘了實際調用該方法,使內容沒有機會成爲可讀呢。

f.close()