为什么要更改文件名?

Why is the file name being changed?

我在 Python 中创建了一个自动脚本,用于使用 unsplash.com API 更改桌面上的墙纸。它运行良好,除了当我告诉它将文件保存为 wallpaper.jpg 时,它会执行一次,然后保存的每个文件都保存为 wallpaper(1).jpg。为什么会这样?我希望将文件简单地保存为 wallpaper.jpg.

我解决了 change_wallpaper 函数中的问题,以便它检索 wallpaper(1).jpg 文件,但如果可能的话我宁愿不必这样做。

# 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()

如果 wget 模块没有覆盖现有文件的功能,您需要先删除现有文件,然后再尝试下载新文件。您可以在您的代码中执行此操作,如下所示。

import os

if os.path.exists(filename):
    os.remove(filename)