renaming filenames while also creating a copy?

Viewed 52

I have spent the last 4 hours trying to solve this problem. I am downloading images from a website and storing them in Users/Temp. What I want to do is, when downloading an image, check the temp folder to see if there are any already there with the same name. If there are, then rename them using an f string and a counter, but still download and save them.

 for bmp in bmp_list:
        fullfilename = os.path.join(f'{dl_location}', f'{bmp}')
        dl_link = url + bmp
        urllib.request.urlretrieve(dl_link, fullfilename)

        if os.path.isfile(fullfilename):
            print('file already exists, renaming.')
            os.rename(fullfilename, f'copy{c}-{fullfilename}')
            c =+1
        else: None

I know that my code is creating the file, then checking if it is there and obviously it is there because I just copied it, but I am quite stuck. Help would be greatly appreciated!

EDIT: when i run this code I get the error message

FileNotFoundError: [Errno 2] No such file or directory: '/Users/Home/Temp/CW/monty-python-(1).bmp' -> 'copy1-/Users/Home/Temp/CW/monty-python-(1).bmp'
1 Answers

The problem seems to be that you prefix an absolute path with copy{c}. Use a suffix instead:

os.rename(fullfilename, f'{fullfilename}-copy{c}')

Also, you need to rename the existing file before downloading. After downloading is too late, the original file is already gone. So move the if statement before the download step.

Finally, a drawback of using a simple suffix is that it goes after the filename extension .bmp. A simple remedy could be to use f'{fullfilename}-copy{c}.bmp' as the new name, with the drawback that there will be .bmp` twice. If that's an issue for you, then you can do better with a bit more work, splitting the base name and the extension, and using the base name to format the new name in the desired format.

Related