我正在编写一些代码,这些代码应该在Python2.7.x和Python下运行,并且使用Unicode数据文本文件I/O。
那么哪个更好-和为什么?
变式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一样,只是为Python2.7.x提供后端存根。它看起来也很干净,我不需要修改现有的代码。此外,我认为,也许我可以节省一点,不导入整个io模块。
发布于 2016-11-25 17:23:44
正如@smido在一条评论中指出的那样,open
是Python2和3的内置版本,那么它在两个版本的Python中都是可用的,没有任何导入。
现在,假设您询问导入包的更好方法是什么,即import module
vs from module import ...
,在形式上没有更好的方法,这取决于您,但我认为使用变体1是好的,因为如果您将使用另一个具有名为open()
的函数的模块,最后一个导入将覆盖前者。
您是对的,在Python3中通常使用from module import field
是非常普遍的,但我个人会使用第一个变体。最后,如果您担心输入更多的内容,那么一个好的编辑器或IDE将对您有所帮助。:-)
https://stackoverflow.com/questions/40809901
复制相似问题