【问题标题】:Why is the file name being changed?为什么要更改文件名?
【发布时间】:2021-10-20 10:18:06
【问题描述】:

我在 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()

【问题讨论】:

  • wallpaper(1).jpg 类型的文件名听起来像是在使用来自 Windows 操作系统的某种文件副本,它将重命名新文件,这样它就不会覆盖任何现有文件。可以先删除原文件吗?
  • 是的,所以即使我删除了这两个文件(wallpaper.jpg 和 wallpaper(1).jpg)并运行脚本,它也会创建一个 wallpaper.jpg 文件,然后是一个 wallpaper(1).jpg文件。

标签: python automation save wget wallpaper


【解决方案1】:

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

import os

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

【讨论】:

  • 成功了!我将条件语句放在 get_wallpaper 函数的开头,以便每次运行程序时都会调用它。 ``` def get_wallpaper(): if os.path.exists('tmp/wallpaper.jpg'): os.remove('tmp/wallpaper.jpg') ...... ```谢谢!
猜你喜欢
  • 2020-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
相关资源
最近更新 更多