I am trying to make a backup copy of an image, because it will be resized often. I am asking for the path where the image is (Tkinter), then I am adding to the path and the image an "-original" and save it in the same directory where I got it from.
The problem is everytime I use this function it overrides the original, because there is no loop which makes the programm check wheter there already exists a file with "-original".
Thats how I make the backup save:
pfad = askopenfilename()
im_backup = Image.open(pfad)
start_string = pfad[:pfad.index(".")]
ende_string = pfad[pfad.index("."):]
im_backup.save(start_string + "-original" + ende_string)
Currently I am working on a solution with os which could work, but I have the feeling it has to be simple. I red the documentation of PIL.Image.save, there are more arguments which can be passed in to save, but I dont figured out which one has to be used to prevent overriding.
My current solution (not working yet) is checking with os.listdir(directory) wether there is already a (start_string + "-original" + ende_string) file and only save it there if it is false.
Thanks in advance!
Consider using os.path.splitxext
instead of slicing and indexing. You can also use os.path.isfile
instead of listdir
.
import os
pfad = askopenfilename()
name, ext = os.path.splitext(pfad)
backup_name = name + "-original" + ext
if not os.path.isfile(backup_name):
im_backup = Image.open(pfad)
im_backup.save(backup_name)
It's probably bot possible to do what you want by passing something to .save()
.
The thing in the docs that probably made you think that it's possible is this:
But in the source code there are lines,
self.encoderinfo = params
self.encoderconfig = ()
in which all the options are stored in a variable that has relation to encoder, so it's probably not what you want.
So, you should probably consider doing what @Kevin suggested.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.