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

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 :
folder/image_title.jpg
copying the image
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

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.

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))

install exiftool
and run command in the photo path:
exiftool -d "./%Y-%m-%d" "-directory

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 ?

Related

File Path Concatenation

I need to build a Windows (only) file path from a combination of a UNC path passed to my script as a parameter, an API call, and a calculated date.
I'm having a horrible time of it, mostly caused by Windows' use of a backslash character to delimit file paths. I've read that the "pathlib" module should be able to sort this mess out, BUT it apparently doesn't support concatenation when building out file paths.
The UNC path is being passed out to the script as a dictionary from another application (PRTG Network Monitor:
{"fileshare": "//server02/logs/"}
I read that in and then need to append a hostname derived from an API call:
logPath = Path(params["fileshare"] + "/" + apiHostname + "/")
I then calculate a date which needs to be appended to the logpath, along with a delimiter "-" and a filename suffix:
filePath = Path(logPath, + apiHostname + "-", + past_day + ".log" )
The problem arises during the concatenation:
{"text": "Python Script execution error: unsupported operand type(s) for +: 'WindowsPath' and 'str'", "error": 1}}
Can someone please explain how I can build a path so that the calculated filename, which should look like this:
\\server02\logs\log01.rhmgmt.lan\log01.rhmgmt.lan-2021-07-28.log
Can be opened for processing?
Yes "pathlib" module should be able to sort this mess out
Input:
from datetime import date, timedelta
from pathlib import Path
params = {"fileshare": "//server02/logs/"}
apiHostname = 'log01.rhmgmt.lan'
past_day = str((date.today() - timedelta(days=1)))
Create the initial path and append all parts:
fileshare = Path(params['fileshare'])
filepath = fileshare / apiHostname / f"{apiHostname}-{past_day}.log"
Output:
>>> filepath
PosixPath('//server02/logs/log01.rhmgmt.lan/log01.rhmgmt.lan-2021-07-28.log')
Yes, pathlib can easily sort things out.
You can use the joinpath() method, as I suggested in a comment, to concatenate the components are you're building the Path. It does the equivalent of what os.path.join() does.
The only slightly tricky part is you'll have to initially create an empty Path in order use the method they inherit from PurePath.
from datetime import date, timedelta
from pathlib import Path
params = {"fileshare": "//server02/logs/"}
apiHostname = 'log01.rhmgmt.lan'
past_day = str((date.today() - timedelta(days=1)))
filePath = Path().joinpath(params["fileshare"], apiHostname,
apiHostname + '-' + past_day + '.log')
print(filePath) # -> \\server02\logs\log01.rhmgmt.lan\log01.rhmgmt.lan-2021-07-29.log

FileNotFoundError when using os.rename() in Python

I'm following this post to rename the file name, but I got error below, I've tried lots of potential solutions I can find here but none of solves my issue:
import os
import datetime
current_date = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
current_date
os.rename(r'C:\Users\...\xxxx.csv', r'C:\Users\...\xxxx_' + str(current_date) + '.csv'
The Error is:
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\...\\xxx.csv -> 'C:\\Users\\...\\xxx_2020-04-14 16:43:56.csv'
How can I solve it?
It doesn't Seem to like the format of current_date
import os
import datetime
current_date = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
old = 'C://path//somefile.csv'
new = 'C://path//somefile'+'new.csv' #str(current_date)+'.csv'
os.rename(old,new)
This worked for me (windows), You can't use certain characters in filenames, in this case it's the ":" thats causing problems, changing it to '-' should solve it.
maybe the file really doesnt exist in your path.. use os.walk to check if the file inside the folder, just like this:
for _ in os.walk(path):
print(_)

Creating Modules and using them

I am playing around with creating modules.I have two python scripts.The first (the module) has:
def abspath(relpath):
import os
absdir = os.path.realpath('__file__')
absdir = absdir.split('_')[0].replace('\\', '/')
filename = str(absdir + relpath )
print (filename)
return filename;
The second file (main) has:
import file_tools as ft
filename = ft.abspath('some/path/')
When I run Main, filename appears empty (Type:None). I have run the filename = abspath(etc) within the 'module', and it works. Clearly, I am missing something here!!
and doing this, so any help would be useful.
Thank's all.
MT
The problem lies in how you're finding the working directory; the preferred method being os.getcwd() (or os.getcwdb for Unix compatibility). Using that, we can see that your function boils down to:
def abspath(relpath):
return os.path.join(os.getcwd(), relpath)

Creating a folder in the "AppData\Roaming" directory [Python]

Is there actually a way of doing this? I've tried using the following code:
file_path = os.environ['APPDATA'] + "\\Example\\example.db"
sqlite3.connect(file_path)
But it comes up with an error. My only thought would be that it's permissions-related, but if that was the case, then I probably wouldn't create a file there, either... I'm stumped. Anyone got any idea?
Try like this,
import os
dir_path = '%s\\Example\\' % os.environ['APPDATA']
if not os.path.exists(dir_path):
os.makedirs(dir_path)
file_path = '%sexample.db' % dir_path
sqlite3.connect(file_path)

shutil.move doesn't delete source files

Newish Python guy here. I've written what I thought would be a fairly simple script to extract the creation date metadata from photos and video and move them to a new folder based on year and month. I'm using PIL for picture and hachoir for video metadata.
For the most part I've got it working until I actually use shutil.move. At that point all the jpg's move to the new folders just fine. But all the videos are being COPIED. The original files are being left in the source folder.
My assumption is that some process that I invoke during the script is still accessing the video file and not letting it be deleted. Can anyone tell me what I'm messing up, and how I can release these video files to be moved?
========================
import os.path, time, sys, shutil
from PIL import Image
from PIL.ExifTags import TAGS
from hachoir_core.error import HachoirError
from hachoir_core.cmd_line import unicodeFilename
from hachoir_parser import createParser
from hachoir_core.tools import makePrintable
from hachoir_metadata import extractMetadata
from hachoir_core.i18n import getTerminalCharset
def get_field (exif,field) :
for (k,v) in exif.iteritems():
if TAGS.get(k) == field:
return v
for picture in os.listdir(os.getcwd()):
if picture.endswith(".jpg") or picture.endswith(".JPG"):
print picture
rawMetadata = Image.open(picture)._getexif()
datetime = get_field(rawMetadata, 'DateTime')
datedict = {'year' : datetime[0:4], 'month' : datetime[5:7]}
target = datedict['year']+'-'+ datedict['month']
if not os.path.isdir(target):
newdir = os.mkdir(target)
if picture not in target:
shutil.move(picture, target)
if picture.endswith('.mov') or picture.endswith('.MOV') or \
picture.endswith('mp4') or picture.endswith('.MP4'):
picture, realname = unicodeFilename(picture), picture
parser = createParser(picture, realname)
rawMetadata = extractMetadata(parser)
text = rawMetadata.exportPlaintext()
datedict = {'year' : text[4][17:21], 'month' : text[4][22:24]}
target = datedict['year']+'-'+ datedict['month']
dest = os.path.join(target, picture)
if not os.path.isdir(target):
newdir = os.mkdir(target)
if picture not in target:
try:
shutil.move(picture, dest)
except WindowsError:
pass
The in operator says whether items are in collections (e.g. an element in a list) or strings are substrings of other strings. It doesn't know that your string variable target is the name of a directory, nor does it know anything about checking directories to see if files are in them. Instead, use:
if os.path.exists(dest):
It's hard to tell what exactly is failing without a decent error code. Use this in your except block to get more answers:
except WindowsError as e:
print("There was an error copying {picture} to {target}".format(
picture=picture,target=target))
print("The error thrown was {e}".format
(e=e))
print("{picture} exists? {exist}".format(
picture=picture, exist=os.exists(picture))
print("{target} exists? {exist}".format(
target=target,exist=os.exists(target))
Note that much can be said for the logging module for errors like these. It's rather outside the scope of this question, though.

Categories

Resources