json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1


问题描述:使用Python代码将txt城市列表文件转换为xls文件,源码如下,

#!/usr/bin/env Python
# coding=utf-8
import os
import json
import xlwt
 
# 存放文件的目录
filepath = '/home/tarena/python/20180312'
 
 
def run():
    os.chdir(filepath)
    # 读取文件内容
    with open('city.txt') as f:
        content = f.read()
    # 转为json
    d = json.loads(content)
    file = xlwt.Workbook()
    # 添加sheet
    table = file.add_sheet('test')
    for row, i in enumerate(list(d)):
        table.write(row, 0, i)
        table.write(row, 1, d[i])
    file.save('city.xls')
 
if __name__ == "__main__":
    run()

报错误:json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)错误,

分析原因是因为txt文件包含BOM字符,去掉BOM字符,在content = f.read()代码下加上:

if content.startswith(u'\ufeff'):
      content = content.encode('utf8')[3:].decode('utf8')

 

转载于 https://blog.csdn.net/liu_xzhen/article/details/79563782


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM