簡體   English   中英

如果文件已經存在,如何迭代地重命名文件(Python)

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

我有一個圖像 URL 列表,我想用 urllib 迭代檢索。 我發現的問題是,一旦我指定了要保存的圖像的文件路徑,我就無法迭代地更改文件路徑以反映新文件的命名方式應與舊文件不同的事實。

因此,例如說我的原始文件路徑是'C:\something\something_else\01.png' ,我想將其更改為'C:\something\something_else\02.png' 我認為代碼可能類似於以下內容:

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

任何幫助將不勝感激!

path參數可以是任何你想要的。 更改文件名的簡單方法如下:

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

這將為您列表中的每個文件提供一個唯一編號

要添加到 CumminUp07 的答案,您還可以添加檢查以查看文件是否已存在:

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)

CumminUp07 之前已經給出了解決方案。 我建議如果 URL 直接用於圖像,並且大多數命名為“正常”(例如“http://example.com/image.png”),那么您可以嘗試將文件命名為源圖像:

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)

您還可以添加 Kevin G 提出的 if 條件,以避免在圖像始終命名相同的情況下覆蓋和丟失圖像:

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)

您還可以解構 filenameToUse 變量以將索引 i 添加到末尾而不是開頭,但您得到了它的要點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM