Python写txt。将固定的页眉和页脚合并到txt中的变量数据

时间:2019-03-09 12:03:57

标签: python scrapy

我难以最终确定搜寻器(更确切地说,是在txt的输出文件中)。 它必须有一个页眉(h)和一个页脚(p),只能写一次。以及由Scrapy生成的可变数据(col)。目前,我已经手动添加了页眉和页脚,并且正在寻找一种使过程自动化的方法。 我知道纯文本文件没有页眉和页脚。但是有什么方法可以模拟这种情况而不必诉诸外部模块吗?

filename = item['cat'] + '.txt'

            f= open(filename,'a')
            h = ('As últimas notícias')
            p = ('Você só encontra aqui')
            col = ('item['title'] \n + item ['author']\n + item['img']\n\n+ item['news']')
            f.write('h \n + col \n + p')
            f.close()

所需的输出:

As últimas notícias

title here
author here
img link here
news here

title here
author here
img link here
news here

title here
author here
img link here
news here

title here
author here
img link here
news here

Você só encontra aqui

1 个答案:

答案 0 :(得分:1)

也许您可以使用如下所示的管道:http://doc.scrapy.org/en/latest/topics/item-pipeline.html#write-items-to-a-json-fileopen_spider中,您将创建文件描述符并编写标头,在close_spider上创建页脚并关闭文件描述符,并使用process_item来编写内容。

您还可以使用类似的主题来检查此主题:Scrapy pipeline spider_opened and spider_closed not being called

UPD:

class MySpider(Spider):
    files = {}

    def parse(self, response):
         # create you item and then:
         if item['cat'] in self.files:
             f = self.files[item['cat']]
         else:
             f = open(item['cat'] + '.txt', 'a')
             f.write('As últimas notícias')
             self.files[item['cat']] = f

         f.write('col \n')

然后在spider_closed上进行self.files的迭代,编写页脚和结束描述符。