Difference between open and codecs.open in Python

前端 未结 8 526
一整个雨季
一整个雨季 2020-12-04 09:53

There are two ways to open a text file in Python:

f = open(filename)

And

import codecs
f = codecs.open(filename, encoding=\         


        
8条回答
  •  执念已碎
    2020-12-04 10:09

    codecs.open, i suppose, is just a remnant from the Python 2 days when the built-in open had a much simpler interface and fewer capabilities. In Python 2, built-in open doesn't take an encoding argument, so if you want to use something other than binary mode or the default encoding, codecs.open was supposed to be used.

    In Python 2.6, the io module came to the aid to make things a bit simpler. According to the official documentation

    New in version 2.6.
    
    The io module provides the Python interfaces to stream handling.
    Under Python 2.x, this is proposed as an alternative to the
    built-in file object, but in Python 3.x it is the default
    interface to access files and streams.
    

    Having said that, the only use i can think of codecs.open in the current scenario is for the backward compatibility. In all other scenarios (unless you are using Python < 2.6) it is preferable to use io.open. Also in Python 3.x io.open is the same as built-in open

    Note:

    There is a syntactical difference between codecs.open and io.open as well.

    codecs.open:

    open(filename, mode='rb', encoding=None, errors='strict', buffering=1)
    

    io.open:

    open(file, mode='r', buffering=-1, encoding=None,
         errors=None, newline=None, closefd=True, opener=None)
    

提交回复
热议问题