Python PIL save Image in directory no override if the name is same
Question: 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!


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

