【问题标题】:Using UTF-8 to open file for reading使用 UTF-8 打开文件进行读取
【发布时间】:2014-02-13 13:59:47
【问题描述】:

我正在使用下面的代码,但需要打开它以指定 utf-8 进行阅读。请问我该怎么做?

infile = file(logPath)
lines = infile.readlines()

【问题讨论】:

    标签: python utf-8 readlines


    【解决方案1】:

    使用codecs模块的open函数:

    import codecs
    
    with codecs.open(logPath, encoding='utf8') as infile:
        lines = infile.readlines()
    

    默认codecs.open函数,以rb(读取二进制)模式打开文件:

    def open(filename, mode='rb', encoding=None, errors='strict', 缓冲=1):

        ...
        Files are always opened in binary mode, even if no binary mode
        was specified. This is done to avoid data loss due to encodings
        using 8-bit values. The default file mode is 'rb' meaning to
        open the file in binary read mode.
    

    【讨论】:

    • 我可以使用这个 infile = open(logPath, encoding='utf8')
    • 这给了我错误:infile = open(logPath, encoding='utf8') TypeError: 'encoding' is an invalid keyword argument for this function
    • 现在使用 infile = codecs.open(logPath, encoding='utf8') 有人看到这有什么问题吗?
    • 我没有发现问题?你有问题吗?
    • 不,在Python 2中,你不能使用open(logPath, encoding='utf8'),因为它是一个内置的open函数,与codecs.open函数不同。但在Python 3 中,您可以使用内置的open 函数,但它与codecs.open 函数仍然不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 2012-01-05
    相关资源
    最近更新 更多