【问题标题】:read json file with german characters python 2 (ironpython)读取带有德语字符python 2(ironpython)的json文件
【发布时间】:2021-05-03 16:53:31
【问题描述】:

我正在使用 Ironpython,因此使用 python 2 并读取带有德语字符的 .json 文件我正在使用 encoding='utf-8' 但我收到以下错误:open() got an unexpected keyboard argument 'encoding'.

这里是代码示例:

   def get_data(self):
        #Open and read data from json file into dict
        with open(self.file, encoding='utf-8') as j_file:
            data_dict = json.load(j_file)
            return data_dict

【问题讨论】:

标签: python json python-2.7 encoding ironpython


【解决方案1】:

python 2.x 不支持encoding 参数。您必须导入io 模块来指定编码

open Function - pythontips

import io

   def get_data(self):
        #Open and read data from json file into dict
        with io.open(self.file, encoding='utf-8') as j_file:
            data_dict = json.load(j_file)
            return data_dict

【讨论】:

    【解决方案2】:

    Python 2 也不直接支持 open 函数。

    如此处所示:https://stackoverflow.com/a/30700186/12711820

    你可以这样使用:

    import codecs
        f = codecs.open(fileName, 'r', errors = 'ignore')
    

    【讨论】:

      【解决方案3】:

      open 中的 encoding 参数是在 Python 3 中添加的。如果要在 python 2.x 中使用编码,请使用以下代码:

      import io.open
      
      f = io.open('file.json', encoding='utf-8')
      # Do stuff with f
      f.close
      

      【讨论】:

        猜你喜欢
        • 2021-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-22
        • 1970-01-01
        • 2016-07-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多