Python-何时使用文件vs打开

时间:2020-03-06 14:31:19  来源:igfitidea点击:

用Python打开文件和文件有什么区别?我什么时候应该使用哪个? (假设我处于2.5级)

解决方案

我们应该始终使用open()

如文档所述:

When opening a file, it's preferable
  to use open() instead of invoking this
  constructor directly. file is more
  suited to type testing (for example,
  writing "isinstance(f, file)").

另外,自Python 3.0以来,已删除file()

从功能上来说,两者是相同的; open仍然会调用file,所以目前的区别在于样式。 Python文档建议使用open

When opening a file, it's preferable to use open() instead of invoking the file constructor directly.

原因是在将来的版本中不能保证它们是相同的(" open"将成为工厂函数,根据其打开的路径返回不同类型的对象)。

原因有两个:python的哲学"应该有一种实现方法",而file正在消失。

file是实际的类型(例如使用file('myfile.txt')调用其构造函数)。 open是一个工厂函数,它将返回一个文件对象。

在python 3.0中,"文件"将从内置形式转变为由io库中的多个类实现(有点类似于带有缓冲读取器的Java等)。

仅使用open()打开文件。 file()实际上是在3.0中删除的,此刻已弃用。他们之间有一种奇怪的关系,但是file()现在正在进行中,因此不再需要担心。

以下来自Python 2.6文档。 [括号内的内容]由我添加。

When opening a file, it’s preferable to use open() instead of invoking this [file()] constructor directly. file is more suited to type testing (for example, writing isinstance(f, file)

Van Rossum先生说,尽管open()当前是file()的别名,但我们应该使用open(),因为将来可能会改变。

file()是一种类型,例如int或者列表。 open()是用于打开文件的函数,它将返回一个file对象。

这是何时应使用open的示例:

f = open(filename, 'r')
for line in f:
    process(line)
f.close()

这是何时应使用文件的示例:

class LoggingFile(file):
    def write(self, data):
        sys.stderr.write("Wrote %d bytes\n" % len(data))
        super(LoggingFile, self).write(data)

如我们所见,存在两者的充分理由和明确的用例。