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