Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is open() preferable over file() in Python? [duplicate]

Tags:

python

file

Possible Duplicate:
Python - When to use file vs open

From the official python documentation,

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

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

But it doesn't give a reason.

like image 943
balki Avatar asked Aug 13 '12 21:08

balki


People also ask

Why is it best to open a file with with in Python?

With the “With” statement, you get better syntax and exceptions handling. “The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.” In addition, it will automatically close the file. The with statement provides a way for ensuring that a clean-up is always used.

What is the difference in opening a file using open () function or using with statement?

Benefits of calling open() using “with statement” So, it reduces the number of lines of code and reduces the chances of bug. If we have opened a file using “with statement” and an exception comes inside the execution block of “with statement”. Then file will be closed before control moves to the except block.

Why is with open better?

It eliminates the need to write your own finally blocks, and it structures your code such that you avoid duplicative if statements, and it allows readers to easily locate the place where a file object (or rather variable holding a file object) is defined.

What is the difference between with open and open in Python?

Part 1: The Difference Between open and with open Basically, using with just ensures that you don't forget to close() the file, making it safer/preventing memory issues.


1 Answers

The Zen of Python:

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

So either file or open should go.

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

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

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

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.

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

This answer is very similar to @Ryan's answer.

In addition BDFL said:

"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)

like image 83
jfs Avatar answered Oct 14 '22 06:10

jfs