簡體   English   中英

json文件在使用python放入zip存檔時遭到損壞

[英]json file get's damaged while putting it into a zip archive with python

在抓取抓取的網站之后,我要在關閉方法中創建一個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導出器將在close_spider()期間寫入文件,這已經很晚了。

這很容易做到。

將JsonItemExporter加載到文件pipelines.py中

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包含問題中提到的郵政編碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM