如何在Python 2中使用“encoding”参数作为open()函数?

时间:2016-10-17 19:49:35

标签: python encoding decode

这里全新的Python ......我希望这不是一个愚蠢的问题。

尝试遵循以下帖子:

  1. Is 'encoding is an invalid keyword' error inevitable in python 2.x?
  2. Ansi to UTF-8 using python causing error
  3. 但无法真正解决我的问题。

    所以我这里有一个Python 3格式的代码块:

    with open(fresh_file,'r', encoding='latin-1') as targ_f:
    new_data_iter = csv.reader(targ_f,
                           delimiter = ',',
                           quotechar = '"')
    new_data = [new_data for new_data in new_data_data_iter]
    

    我有Python 2,所以我想更改此代码,以便它与Python 2兼容。

    以上是我到目前为止阅读过以上帖子的内容:

    with open(fresh_file,'r') as targ_f:
    new_data_iter = csv.reader(targ_f.decode('latin-1'),
                           delimiter = ',',
                           quotechar = '"')
    new_data = [new_data for new_data in new_data_data_iter]
    

    然后我收到错误代码:

    AttributeError: 'file' object has no attribute 'decode'
    

    所以我读了decode()文档,它只能在字符串对象上完成,因为我的target_f是一个文件对象,所以无法应用它。但是new_data_iter是一个cvs.reader类型的obj,因此也无法应用。现在,我不确定如何将decode()合并到python 2代码中......

0 个答案:

没有答案