多个文件,我想使用scrapy网络刮后,他们将文件保存到一个目录。我从文件中提取一个日期并将其用作文件名。但是,我遇到的问题是,某些文件具有相同的日期,即有两个文件名称为“2009年6月2日”。所以,我想要做的是以某种方式检查是否已经有一个相同名称的文件,如果是,请将其命名为“June 2,2009.1”或类似名称。命名Python和scrapy
我正在使用的代码如下:
def parse_item(self, response):
self.log('Hi, this is an item page! %s' % response.url)
response = response.replace(body=response.body.replace('<br />', '\n'))
hxs = HtmlXPathSelector(response)
date = hxs.select("//div[@id='content']").extract()[0]
dateStrip = re.search(r"([A-Z]*|[A-z][a-z]+)\s\d*\d,\s[0-9]+", date)
newDate = dateStrip.group()
content = hxs.select("//div[@id='content']")
content = content.select('string()').extract()[0]
filename = ("/path/to/a/folder/ %s.txt") % (newDate)
with codecs.open(filename, 'w', encoding='utf-8') as output:
output.write(content)
这是好的,只要你的Python脚本是创建这些文件的唯一进程。如果你在并行与其他程序的工作有一个[微妙的竞争条件(http://stackoverflow.com/questions/82831/how-do-i-check-if-a-file-exists-using-python)你可能需要考虑。 – 2012-04-17 07:00:28