【问题标题】:Python: encoding a file as you write itPython:在编写文件时对其进行编码
【发布时间】:2017-05-31 18:43:35
【问题描述】:

我正在使用 python 2.7,我正在尝试使用某种编码编写一个文件(在我的“finalList”变量中,编码是:0xe9)

这就是我尝试使用“json”和“io”模块编写文件的方式

import json
import io

with io.open('my.json', 'w', encoding='utf8') as outfile:
    json.dump(finalList, outfile)

【问题讨论】:

标签: python json python-2.7 encode


【解决方案1】:

json.dump 接受 encoding arg,默认为 'utf-8':

$ pydoc json.dump
Help on function dump in json:

json.dump = dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, sort_keys=False, **kw)

【讨论】:

  • 使用 python 3.4:json.dump(dict(),io.StringIO(),encoding='utf-8') 给我:TypeError: __init__() got an unexpected keyword argument 'encoding'
  • 问题标记为python2.7
猜你喜欢
  • 1970-01-01
  • 2019-09-03
  • 2016-12-09
  • 2016-01-27
  • 2010-09-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 2011-11-14
相关资源
最近更新 更多