Difference between open and codecs.open in Python

前端 未结 8 489
一整个雨季
一整个雨季 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:11
    • When you want to load a binary file, use f = io.open(filename, 'b').

    • For opening a text file, always use f = io.open(filename, encoding='utf-8') with explicit encoding.

    In python 3 however open does the same thing as io.open and can be used instead.

    Note: codecs.open is planned to become deprecated and replaced by io.open after its introduction in python 2.6. I would only use it if code needs to be compatible with earlier python versions. For more information on codecs and unicode in python see the Unicode HOWTO.

    0 讨论(0)
  • 2020-12-04 10:13

    When you're working with text files and want transparent encoding and decoding into Unicode objects.

    0 讨论(0)
提交回复
热议问题