问题描述:使用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