【发布时间】:2017-10-26 10:01:14
【问题描述】:
我有一个 Python 脚本来读取 JSON 文件的内容并导入到 MongoDB。
我收到以下错误:
Traceback (most recent call last):
File "/home/luke/projects/vuln_backend/vuln_backend/mongodb.py", line 39, in process_files
file_content = currentFile.read()
File "/home/luke/envs/vuln_backend/lib64/python3.6/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 14: invalid continuation byte
这是代码:
import json
import logging
import logging.handlers
import os
import glob
from logging.config import fileConfig
from zipfile import ZipFile
from pymongo import MongoClient
def process_files():
try:
client = MongoClient('5.57.62.97', 27017)
db = client['vuln_sets']
coll = db['vulnerabilities']
basepath = os.path.dirname(__file__)
filepath = os.path.abspath(os.path.join(basepath, ".."))
archive_filepath = filepath + '/vuln_files/'
archive_files = glob.glob(archive_filepath + "/*.zip")
for file in archive_files:
with open(file, "r") as currentFile:
file_content = currentFile.read()
vuln_content = json.loads(file_content)
for item in vuln_content:
coll.insert(item)
except Exception as e:
logging.exception(e)
我尝试将编码设置为 UTF8 和 Windows-1252,但这些似乎也无法读取 JSON。
如何获取它来确定 JSON 中使用了哪种编码?
【问题讨论】:
-
好吧,你必须在阅读文件之前解压缩文件......你甚至导入了模块但不使用它。
-
我已经盯着这个看了几个小时.....我完全忘记了添加那个代码!我想我已经把代码弄瞎了!感谢您指出这一点!
-
“新鲜的一双眼睛”......正如他们所说。不客气。
-
您能否将其作为答案,以便我接受并给予声誉?
-
完成,谢谢。我还尝试用其他“最佳编程”技巧来证实我的答案。希望他们有所帮助。