V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
cfans1993
V2EX  ›  问与答

如何让 Python 输出文件的内容为汉字而不是\u5f71 这种形式的字符

  •  
  •   cfans1993 · 2017-04-01 10:45:54 +08:00 · 1656 次点击
    这是一个创建于 2644 天前的主题,其中的信息可能已经有所发展或是发生改变。

    不熟悉 python,想用 python 把 xls 文件转成 json 格式,用了下面的代码,在 python shell 能正常输出中文,可是一保存到文件里就是\u 的形式,环境为 win7 x64,python 3.6,不知道要怎么解决

    import xlrd
    from collections import OrderedDict
    import json
    import codecs
    
    wb = xlrd.open_workbook('1.xls')
    
    convert_list = []
    sh = wb.sheet_by_index(0)
    title = sh.row_values(0)
    for rownum in range(1, sh.nrows):
        rowvalue = sh.row_values(rownum)
        single = OrderedDict()
        for colnum in range(0, len(rowvalue)):
            print(title[colnum], rowvalue[colnum])
            single[title[colnum]] = rowvalue[colnum]
        convert_list.append(single)
        
    j = json.dumps(convert_list)
    
    with codecs.open('file.json',"w","utf-8") as f:
        f.write(j)
    
    
    1 条回复    2017-04-01 10:56:32 +08:00
    cfans1993
        1
    cfans1993  
    OP
       2017-04-01 10:56:32 +08:00
    找到问题了, 原来是 json_dumps 的原因,需加加上 ensure_ascii=False
    json.dumps(convert_list,ensure_ascii=False,indent=2)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   4639 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 09:46 · PVG 17:46 · LAX 02:46 · JFK 05:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.