English 中文(简体)
p和报废的多个档案
原标题:Naming multiple files in python and scrapy

I m trying to save files to a directory after scraping them from the web using scrapy. I m extracting a date from the file and using that as the file name. The problem I m running into, however, is that some files have the same date, i.e. there are two files that would take the name "June 2, 2009". So, what I m looking to do is somehow check whether there is already a file with the same name, and if so, name it something like "June 2, 2009.1" or some such.

使用Im的代码如下:

def parse_item(self, response):
    self.log( Hi, this is an item page! %s  % response.url) 

    response = response.replace(body=response.body.replace( <br /> ,  
 ))

    hxs = HtmlXPathSelector(response)

    date = hxs.select("//div[@id= content ]").extract()[0]
    dateStrip = re.search(r"([A-Z]*|[A-z][a-z]+)sd*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)
最佳回答
问题回答

你们可以使用os。 收到现有档案清单并分配不会引起冲突的档案名称。

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"

检查C图书馆档案的通常方式是:>>。 灰尘以<代码>os.stat(<>/code>的形式,围绕这一功能提供微薄的包装。 我建议你这样做。

rel=“nofollow>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

one other solution is you can append time with date, for naming file like

from datetime import datetime

filename = ("/path/to/a/folder/ %s_%s.txt") % (newDate,datetime.now().strftime("%H%M%S")) 




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签