Question: I'm scraping a site and saving images to my local. This is working well but some images have different paths but same exact name so they get overwritten in my local even do they are different images.

How can I save all images without overwriting previous ones. I'm thinking of adding a counter prefix to each image name but I can't seem to figure it out. 

Here is the code:

```
    # Save images
    for url in urls:
    filename = re.search(r'([\w_-]+[.](jpg|gif|png))$', url)
    filename = re.sub(r'\d{4,}\.', '.', filename.group(0))

    with open(filename, 'wb') as f:
        if 'http' not in url:
            # sometimes an image source can be relative
            # if it is provide the base url which also happens
            # to be the site variable atm.
            hostname = urlparse(site).hostname
            scheme = urlparse(site).scheme
            url = '{}://{}/{}'.format(scheme, hostname, url)

        # for full resolution image the last four digits needs to be striped
        url = re.sub(r'\d{4,}\.', '.', url)

        print('Fetching image from {} to {}'.format(url, filename))
        response = requests.get(url)
        f.write(response.content)

```

Answer: 
You can write a method as:

```
import datetime

def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
    return datetime.datetime.now().strftime(fmt).format(fname=fname)

```

Open the file as follows:

```
with open(timeStamped(filename),'w') as f:

```

Write the data as:

```
f.write(response.content)

```
Add a timestamp to your file

```
import datetime
import os.path

if os.path.isfile(fname):
    t = datetime.datetime.now()
    fname += t.strftime("%m/%d/%Y")

```