重命名由python下载的图像

时间:2016-06-05 12:54:38

标签: python-3.x

我从以下代码下载了来自不同网址的多个图片。该代码还重命名文件,分配由

计算的1到1000之间的随机数
random.randrange(1,1000)

Insted我希望代码重命名分配有序号码的文件,例如1,2,3,4 我该如何修改代码?

import urllib.request
import random

def download_image(url):

    name=random.randrange(1,1000)
    fullname=str(name)+".jpg"
    urllib.request.urlretrieve(url,fullname)

download_image("https://upload.wikimedia.org/wikipedia/commons/0/0d/D%C3%BClmen%2C_Kirchspiel%2C_Erdbeerfeld_--_2015_--_6492-6.jpg")
download_image("https://upload.wikimedia.org/wikipedia/commons/5/5f/StAngelo_Bridge_Rome.jpg")

1 个答案:

答案 0 :(得分:0)

你需要创建一个int变量来说明它是哪个数字。例如

 numImage = 0 #The int that will determine the name
 def download_image(url):

     name = str(numImage + 1) #The actual name
     if name == "1000": #Making sure it doesn't exceed 1000 as you said
         print("Max images exceeded!")
     else:

         fullname = name + ".jpg"
         urllib.request.urlretrieve(url,fullname)
         print("Saved as %s" % fullname) #Telling the user what it did.