2016-11-25 21 views
0

我正在編寫一些代碼,該代碼應該在Python 2.7.x 下運行,並且Python 3.3+不變,並且使用Unicode數據文本文件I/O。Python 2.7 io.open:使用「從io import open」或「io.open()」?

那麼哪個更好 - 爲什麼?

變體1:

import io 
encoding = 'utf-8' 

with io.open('Unicode.txt', 'w', encoding=encoding) as f: 
    … 
with io.open('Unicode.txt', 'r', encoding=encoding) as f: 
    … 

變2:

from io import open 
encoding = 'utf-8' 

with open('Unicode.txt', 'w', encoding=encoding) as f: 
    … 
with open('Unicode.txt', 'r', encoding=encoding) as f: 
    … 

個人而言,我傾向於使用變2,因爲代碼應爲Python-儘可能提供3- ish,僅爲Python 2.7.x提供後端存根。它看起來更乾淨,我不必更改現有的代碼。另外我想也許我可以通過不導入整個io模塊來節省一點。

+2

您總是導入一個完整的模塊。唯一的區別就是在你當前的模塊全局變量中綁定了什麼名字(所以'io'被綁定,或者'open'被綁定)。 –

+0

不知道,謝謝你的解釋,Martijn! – Moonbase

+0

@MartijnPieters這不是另一個問題的重複。具體到'開放'。使用Variant 2意味着一旦Python 3被完全採用,你就可以刪除整個導入行。 – Emil

回答

0

形式上有沒有更好的辦法,這是你的,但我認爲這是很好的使用,因爲變體1的情況下,你將使用有一個名爲open()功能的另一模塊,最後導入將覆蓋前任的。

你說得對,一般來說在Python 3中使用from module import field非常常見,但我個人會使用第一個變體。最後,如果你擔心輸入更多,一個好的編輯器或IDE會幫助你。 :-)