json文件get在使用python将其放入zip存档时被损坏

2024-10-01 13:24:09 发布

您现在位置:Python中文网/ 问答频道 /正文

在用scrapy爬过一个站点之后,我在closing方法中创建了一个zip存档,将图片拉入其中。 然后我将一个有效的json文件添加到存档中。你知道吗

解压后(在macosx或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()

我可以重复这个错误好几次,其他一切看起来都正常。你知道吗


Tags: 文件topathnamejsondatetimezipfilename
1条回答
网友
1楼 · 发布于 2024-10-01 13:24:09

解决方案是使用scrapy jsonitemexporter而不是fead exporter,因为feed exporter将在close\u spider()期间写入文件,这很晚。你知道吗

这很容易做到。你知道吗

在文件中加载jsonimexporter管道.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方法包含问题中提到的邮政编码。你知道吗

相关问题 更多 >