简体   繁体   中英

How to iteratively rename a file if it already exists (Python)

I have a list of image URLs which I would like to retrieve iteratively with urllib. The issue I am finding is that once I nominate the file path of the image to be saved, I cannot iteratively change the file path to reflect the fact that a new file should be named differently to the old one.

So for example say my original file path is 'C:\something\something_else\01.png' , I'd like to change it to 'C:\something\something_else\02.png' . I think the code might be something along the lines of the following:

for image in list_of_image_URLs:
    urllib.request.urlretrieve(image, path)
    somehow_redefine_the_path_for_next_loop

Any help would be greatly appreciated!

The path argument can be whatever you want it to be. A simple way to change the file name would be something like this:

for i, image in enumerate(list_of_image_URLs):
    path = f"./my_path_{i}.png"
    urllib.request.urlretrieve(image, path)

This will give you a unique number for each file in your list

To add to CumminUp07's answer, you can also add a check to see if the file already exists:

import os

for i, image in enumerate(list_of_image_URLs):
    path = f"./my_path/{i}.png" if os.path.exists(image) else image
    urllib.request.urlretrieve(image, path)

The solution was already given before by CumminUp07. I would suggest that if the URL are for the images directly, and most are named "normally" (eg "http://example.com/image.png"), then you could try naming the file just as the name of the source image:

for i, image in enumerate(list_of_image_URLs):
    filenameToUse = image.split("/")[-1] #Gives "image.pgn" from URL
    path = f"./my_local_path/{filenameToUse}"
    urllib.request.urlretrieve(image, path)

You could also add the if condition as proposed by Kevin G to avoid overwriting and losing images in the off-chance the images are always named the same:

import os    

for i, image in enumerate(list_of_image_URLs):
    filenameToUse = image.split("/")[-1] #Gives "image.pgn" from URL
    path = f"./my_local_path/{filenameToUse}"
    if os.path.exists(path):
        path = f"./my_local_path/{i}_{filenameToUse}" 
    urllib.request.urlretrieve(image, path)

You can also de-construct the filenameToUse variable to add the index i at the end instead of the beginning but you get the gist of it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM