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.
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With