White Shadow White Shadow - 1 year ago 62
Python Question

Downloaded Images does not set as background always?

I am trying to download some images from MomentumDash (for educational purpose only).
I have written the following python code:

import urllib
import os
import random


#Chooses an image between 1 to 14
choice=random.randint(01,14)
print choice

#Downloads images
a=urllib.urlretrieve("https://momentumdash.com/backgrounds/"+"%02d" % (choice,)+".jpg", str(choice)+".jpg")
print a #Tells the image

#Getting the location of the saved image
cwd = os.getcwd()
random=random.choice(os.listdir(cwd))
file =cwd+ '\\' +random

#Making the image to desktop image
import ctypes
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER , 0, file, 3)


The thing is the probability of this progrm to set a image is 1/7 ish.

Most of the times it gives a black background screen.

Where am I wrong?

Answer Source

Try the following. This ensures that the directory listing is filtered to give you only jpg files. A random entry is taken from these. Also os.path.join() is used to safely join your path and name together.

import urllib
import os
import random
import ctypes 

#Chooses an image between 1 to 14
choice = random.randint(1, 14)

#Downloads images
download_name = "{:02}.jpg".format(choice)
a = urllib.urlretrieve("https://momentumdash.com/backgrounds/{}".format(download_name), download_name)

#Getting the location of the saved image
cwd = os.getcwd()

#Filter the list to only give JPG image files
image_files = [f for f in os.listdir(cwd) if os.path.splitext(f)[1].lower() == ".jpg"]
random_image = random.choice(image_files)
full_path = os.path.join(cwd, random_image)

#Making the image to desktop image
SPI_SETDESKWALLPAPER = 20 
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER , 0, full_path, 3)        

The list of files is filtered by using Python's list comprehension feature. This is a way of building a new list from an existing item. In this case it uses the optional if statement to only include files in the new list which have an extension of .jpg.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download