json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1
阿新 • • 發佈:2019-03-11
code 轉換 txt os.chdir nco expec expect enume 轉載
問題描述:使用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
json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1