Python - When to use file vs open
Solution 1:
You should always use open()
.
As the documentation states:
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)").
Also, file()
has been removed since Python 3.0.
Solution 2:
Two reasons: The python philosophy of "There ought to be one way to do it" and file
is going away.
file
is the actual type (using e.g. file('myfile.txt')
is calling its constructor). open
is a factory function that will return a file object.
In python 3.0 file
is going to move from being a built-in to being implemented by multiple classes in the io
library (somewhat similar to Java with buffered readers, etc.)