bl1nk
bl1nk

Reputation: 19

How to copy an image with date in the new filename?

I'm looking for a way to copy an image file from a given source with Python.

I did read several stuff on the internet but what I found was always working just on one specific platform. I would like to know if there exists a functionality in Python that would make it possible to easily copy an image file ?

My target would be to have this in the end :

  1. folder/image_title.jpg
  2. copying the image
  3. new_folder/new_image_title.jpg

with the *new_image_title* being the date of the day.

My code looks like this at the moment :

import shutil
import datetime

shutil.copy('folder/alpha.jpg', 'new_folder/'datetime.date()'.jpg')

But I get an error: SyntaxError: invalid syntax

Upvotes: 0

Views: 1538

Answers (4)

Blackbingo Yan
Blackbingo Yan

Reputation: 89

install exiftool

and run command in the photo path:

exiftool -d "./%Y-%m-%d" "-directory

Upvotes: 0

bl1nk
bl1nk

Reputation: 19

I'm done with it, thanks to you :) So here is my final version, in case it could help other people :

import shutil
import datetime

now = datetime.datetime.now()
date=str(now.year)+'-'+str(now.month)+'-'+str(now.day)

new_folder = "source/new_folder"
dest = new_folder + '/' + str(date) + '.jpg'
shutil.copy('source/alpha.jpg', dest)

One last thing : at the moment, the program just runs without saying anything. So does anyone knows how to print a message saying whether or not the copying did work ?

Upvotes: -1

Levon
Levon

Reputation: 143047

Update:

You probably want a simple string for your second argument:

instead of this:

shutil.copy('folder/alpha.jpg', 'new_folder/'datetime.date()'.jpg')

try:

dest = new_folder + '/' + str(datetime.date(2012, 8, 19)) + '.jpg'
shutil.copy('folder/alpha.jpg', dest)

with:

new_folder = 'bla'

dest becomes:

    'bla/2012-08-19.jpg'

tweak as needed to make the name unique (add time stamp?). Also note, it's usually better to use os.path.join() for creating new paths.

Upvotes: 3

user4815162342
user4815162342

Reputation: 154876

You are getting a SyntaxError because your string forming syntax is incorrect. Corrected, the code would look like this:

import shutil
import datetime
import os

DATE_FORMAT = '%Y-%m-%d'

filename = 'folder/alpha.jpg'
target_folder = 'new_folder'

ext = os.path.splitext(filename)[1]

shutil.copy(filename,
            os.path.join(target_folder, '%s%s'
                         % (datetime.datetime.now().strftime(DATE_FORMAT), ext))

Upvotes: 0

Related Questions