我正在尝试使用scrapy从网上抓取文件后将文件保存到目录中。我正在从文件中提取日期并将其用作文件名。然而,我遇到的问题是某些文件具有相同的日期,即有两个文件名为“2009年6月2日”。所以,我要做的是以某种方式检查是否已经有一个同名的文件,如果是这样,请将其命名为“June 2,2009.1”或类似名称。
我正在使用的代码如下:
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)
答案 0 :(得分:1)
您可以使用os.listdir获取现有文件的列表,并分配不会导致冲突的文件名。
import os
def get_file_store_name(path, fname):
count = 0
for f in os.listdir(path):
if fname in f:
count += 1
return os.path.join(path, fname+str(count))
# This is example to use
print get_file_store_name(".", "README")+".txt"
答案 1 :(得分:0)
检查C库中是否存在文件的常用方法是使用名为stat()
的函数。 Python以os.stat()
的形式提供了围绕此函数的瘦包装器。我建议你使用它。
http://docs.python.org/library/stat.html
def file_exists(fname):
try:
stat_info = os.stat(fname)
if os.S_ISREG(stat_info): # true for regular file
return True
except Exception:
pass
return False
答案 2 :(得分:0)
另一个答案通过检查python中的os工具向我指出正确的方向,但我认为我发现的方式可能更直接。请参阅此处How do I check whether a file exists using Python?了解更多信息。
以下是我提出的代码:
existence = os.path.isfile(filename)
if existence == False:
with codecs.open(filename, 'w', encoding='utf-8') as output:
output.write(content)
else:
newFilename = ("/path/.../.../- " + '%s' ".1.txt") % (newDate)
with codecs.open(newFilename, 'w', encoding='utf-8') as output:
output.write(content)
编辑添加:
我不太喜欢这个解决方案,并且认为另一个答案的解决方案可能更好但不太有用。我不喜欢我的解决方案的主要部分是它只能使用2个同名文件;如果三个或四个文件具有相同的名称,则会出现初始问题。以下是我提出的建议:
filename = ("/Users/path/" + " " + "title " + '%s' + " " + "-1.txt") % (date)
filename = str(filename)
while True:
os.path.isfile(filename)
newName = filename.replace(".txt", "", filename)
newName = str.split(newName)
newName[-1] = str(int(newName[-1]) + 1)
filename = " ".join(newName) + ".txt"
if os.path.isfile(filename) == False:
with codecs.open(filename, 'w', encoding='utf-8') as output:
output.write(texts)
break
它可能不是最优雅的,可能是一种hackish方法,但它到目前为止已经起作用,似乎已经解决了我的问题。
答案 3 :(得分:0)
另一个解决方案是你可以在日期附加时间,用于命名文件,如
from datetime import datetime
filename = ("/path/to/a/folder/ %s_%s.txt") % (newDate,datetime.now().strftime("%H%M%S"))