为什么在Python中open()优于file()? [英] Why is open() preferable over file() in Python?

查看:65
本文介绍了为什么在Python中open()优于file()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Python-何时使用文件vs打开

Possible Duplicate:
Python - When to use file vs open

从官方python文档中,

From the official python documentation,

http://docs.python.org/library/functions.html#file

打开文件时,最好使用open()而不是调用 该构造函数直接

When opening a file, it’s preferable to use open() instead of invoking this constructor directly

但这并没有给出原因.

推荐答案

The Zen Python的:

应该有一种-最好只有一种-显而易见的方法.

There should be one-- and preferably only one --obvious way to do it.

因此fileopen应该都应该消失.

So either file or open should go.

>>> type(file)
<type 'type'>
>>> type(open)
<type 'builtin_function_or_method'>

open是可以返回任何内容的函数. file()仅返回file个对象.

open is a function that can return anything. file() returns only file objects.

尽管看起来open在Python 2上仅返回file对象.在Python 2.5之前,fileopen是同一对象.

Though it seems open returns only file objects on Python 2. And before Python 2.5 file and open are the same object.

正如@gnibbler在评论中建议的那样,file存在的最初原因可能是使用它作为基类的名称.

As @gnibbler suggested in the comments the original reason for the existence of file might be to use it as the name for base classes.

此外,file()原则上可以返回其他类型,例如int()在早期Python版本中所做的操作:

Also, file() in principle could return other types as for example int() did on earlier Python versions:

>>> type(int(2**64)) is long
True
>>> type(int()) is int
True
>>> int is long
False

此答案与 @Ryan的答案非常相似.

此外 BDFL说:

文件类在Python 2.2中是新的.它表示类型(类) 内置的open()函数返回的对象.它的构造函数 是open()的别名,但是为了将来和向后兼容, open()仍然是首选." (强调我的)

"The file class is new in Python 2.2. It represents the type (class) of objects returned by the built-in open() function. Its constructor is an alias for open(), but for future and backwards compatibility, open() remains preferred." (emphasis mine)

这篇关于为什么在Python中open()优于file()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆