python - json 文件在使用 python 放入 zip 存档时损坏
问题描述
用scrapy爬取一个站点后,我在关闭方法中创建了一个zip存档,将图片拉入其中。然后我将一个有效的 json 文件添加到存档中。
解压缩后(在 mac os x 或 ubuntu 上),json 文件将显示损坏。最后一项不见了。
解压文件结束:
..a46.jpg"]},
原始文件:
a46.jpg"]}]
代码:
# create zip archive with all images inside
filename = '../zip/' + datetime.datetime.now().strftime ("%Y%m%d-%H%M") + '_' + name
imagefolder = 'full'
imagepath = '/Users/user/test_crawl/bid/images'
shutil.make_archive(
filename,
'zip',
imagepath,
imagefolder
)
# add json file to zip archive
filename_zip = filename + '.zip'
zip = zipfile.ZipFile(filename_zip,'a')
path_to_file = '/Users/user/test_crawl/bid/data/'+
datetime.datetime.now().strftime ("%Y%m%d") + '_' + name + '.json'
zip.write(path_to_file, os.path.basename(path_to_file))
zip.close()
我可以多次重现此错误,其他一切看起来都很好。
解决方案
解决方案是使用 scrapy jsonitemexporter 而不是 fead exporter,因为 feed exporter 将在 close_spider() 期间写入文件,这已经很晚了。
这很容易完成。
在文件 pipelines.py 中加载 JsonItemExporter
from scrapy.exporters import JsonItemExporter
像这样更改您的管道:
class MyPipeline(object):
file = None
def open_spider(self, spider):
self.file = open('data/test.json', 'wb')
self.exporter = JsonItemExporter(self.file)
self.exporter.start_exporting()
def close_spider(self, spider):
self.exporter.finish_exporting()
self.file.close()
cleanup('zip_method')
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
zip_method 包含问题中提到的邮政编码。
推荐阅读
- python - 以矩阵格式打印列表列表
- java - 从 JavaFX 中的媒体文件中检索元数据专辑封面
- highcharts - 如何在面积图中用单点着色地方 - highcharts?
- node.js - Swagger UI 不会在 NodeJS/Express API 中生成文档
- html - (已解决)html按钮标签如何与Django模板一起使用?
- asp.net-mvc - 我想从外键中的外键获取项目(如果这有任何意义......)
- excel - Countifs 列 I 直到列 a 更改然后保存并重新启动计数
- reactjs - DjangoREST/React - 为什么我的前端/后端令牌认证系统不一致?
- yaml - 需要帮助为什么这个 yaml 失败
- homebrew - Mac OS Big Sur 上的 sstp vpn - 无法完成帧写入,无法将数据包转发到 pppd