I created an automated script in Python to change my wallpaper on my desktop using the unsplash.com API. It runs fine, except when I tell it to save the file as wallpaper.jpg
it does that once, then every file saved thereafter is saved as wallpaper(1).jpg
. Why is this happening? I want the file to be saved simply as wallpaper.jpg
.
I worked around the problem in the change_wallpaper function so that it retrieves the wallpaper(1).jpg
file, but I would rather not have to do this if possible.
# import dependencies
import os
import requests
import wget
import ctypes
import time
from config import UNSPLASH_ACCESS_KEY
def get_wallpaper():
# create API query and define parameters
url = 'https://api.unsplash.com/photos/random?client_id=' + UNSPLASH_ACCESS_KEY
params = {
"query": "HD Wallpapers",
"orientation": "landscape"
}
# create request, define json format, grab image url, and save to folder
response = requests.get(url, params=params).json()
image_url = response['urls']['full']
# download the image
image = wget.download(image_url, 'tmp/wallpaper.jpg')
return image
def change_wallpaper():
get_wallpaper()
# create path using cwd, current working directory, and use ctypes to update the designated image as the wallpaper.
path = os.getcwd()+'\\tmp\\wallpaper (1).jpg'
ctypes.windll.user32.SystemParametersInfoW(20,0, path,3)
def main():
try:
while True:
change_wallpaper()
time.sleep(10)
except KeyboardInterrupt:
print("\nThank you, come again!")
except Exception as e:
pass
if __name__ == "__main__":
main()
If the wget
module doesn't have the capability to overwrite existing files you will need to delete the existing file before you try to download a new one. You can do this within your code as follows.
import os
if os.path.exists(filename):
os.remove(filename)