【发布时间】:2017-10-25 12:13:19
【问题描述】:
我有一个脚本,它从一个文件夹中获取所有 .zip 文件,然后一个接一个地打开 zip 文件,加载其中的 JSON 文件的内容并将其导入 MongoDB。
我得到的错误是the JSON object must be str, bytes or bytearray, not 'TextIOWrapper'
代码是:
import json
import logging
import logging.handlers
import os
from logging.config import fileConfig
from pymongo import MongoClient
def import_json():
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/'
filedir = os.chdir(archive_filepath)
for item in os.listdir(filedir):
if item.endswith('.json'):
file_name = os.path.abspath(item)
fp = open(file_name, 'r')
json_data = json.loads(fp)
for vuln in json_data:
print(vuln)
coll.insert(vuln)
os.remove(file_name)
except Exception as e:
logging.exception(e)
我可以使用单个文件而不是多个文件来完成这项工作,即做一个我写的文件:
from zipfile import ZipFile
import json
import pymongo
archive = ZipFile("vulners_collections/cve.zip")
archived_file = archive.open(archive.namelist()[0])
archive_content = archived_file.read()
archived_file.close()
connection = pymongo.MongoClient("mongodb://localhost")
db=connection.vulnerability
vuln1 = db.vulnerability_collection
vulners_objects = json.loads(archive_content)
for item in vulners_objects:
vuln1.insert(item)
【问题讨论】:
-
尝试用
with open(file, "r")替换file.open(...) / file.close -
我没有使用 glob 的经验,但是从浏览文档中我得到的印象是您的
archive_files是一个简单的文件路径列表作为字符串,对吗?您不能对字符串执行.open之类的操作(因此您的错误),因此请尝试使用上面的命令打开文件。 -
这不行,我只是得到
''str' object has no attribute 'read'的错误