Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between io.open vs open in python

In the past, there's codecs which got replaced by io. Although it seems like it's more advisable to use io.open, most introductory python classes still teaches open.

There's a question with Difference between open and codecs.open in Python but is open a mere duck-type of io.open?

If not, why is it better to use io.open? And why is it easier to teach with open?

In this post (http://code.activestate.com/lists/python-list/681909/), Steven DAprano says that the built in open is using the io.open in the backend. So should we all refactored our code to use open instead of io.open?

Other than backward compatibility for py2.x, are there any reason to use io.open instead of open in py3.0?

like image 657
alvas Avatar asked Nov 24 '15 10:11

alvas


People also ask

What is io Open in Python?

The io module provides Python's main facilities for dealing with various types of I/O. There are three main types of I/O: text I/O, binary I/O and raw I/O. These are generic categories, and various backing stores can be used for each of them.

What is the difference between open and with 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.

What does with open do in Python?

with statements open a resource and guarantee that the resource will be closed when the with block completes, regardless of how the block completes. Consider a file: with open('/etc/passwd', 'r') as f: print f.

Why use with open as Python?

When you use with statement with open function, you do not need to close the file at the end, because with would automatically close it for you. This PEP adds a new statement " with " to the Python language to make it possible to factor out standard uses of try/finally statements.


1 Answers

Situation in Python3 according to the docs:

io.open(file, *[options]*)

This is an alias for the builtin open() function.

and

While the builtin open() and the associated io module are the recommended approach for working with encoded text files, this module [i.e. codecs] provides additional utility functions and classes that allow the use of a wider range of codecs when working with binary files

(bold and italics are my edits)

like image 141
VPfB Avatar answered Sep 21 '22 17:09

VPfB