python讀取文件夾內所有圖片名稱,隨機設置為桌面壁紙且把設置后的圖片移到其他文件夾內的方法


關鍵詞:讀取文件夾、讀取文件、操作系統、設置壁紙、移動文件

 

預期實現如下幾個步驟

1、獲取指定文件夾內所有圖片名

2、隨機取一張圖片設置為壁紙

3、設置為壁紙的圖片移動到另外一個文件夾中

 

第一步,獲取指定文件夾內所有圖片名

  C盤background有兩個文件夾,now文件夾存放是預備設置為壁紙的圖片,ok文件夾存放已經設置為壁紙的圖片

 

  

 

 

 

 

 

 

 

獲取文件夾內所有圖片需要導入os庫,代碼如下

# -*- coding: utf-8 -*-

import os

filePath = 'C:\\background\\'
test = os.listdir(filePath+"now\\")

打印test數列

 

 

 第二部,隨機取值,從獲取的圖片名稱列表中隨機取出一個值,設置為壁紙,需要導入random庫,代碼如下

image_path = random.choice(test)
setWallpaper(filePath+"now\\"+image_path)

定義的設置為壁紙的方法,上方代碼中的setWallpaper

def setWallpaper(image_path):
    key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
    win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
    win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0")
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,image_path, 1+2)

 

第三步,將設置好的圖片移動到其他文件夾內,需要導入shutil庫

shutil.move(filePath+"now\\"+image_path, filePath+"ok\\")

 

如此,實現了開頭的1/2/3步驟,串起來整個腳本如下,可放在桌面上,壁紙看膩了,點一下就切換了,換個思路,可以從網上直接取圖設置壁紙也是可行的

# -*- coding: utf-8 -*-
import win32api
import win32con
import win32gui
import os
import random
import shutil

#設置圖片為桌面背景,參考地址https://blog.csdn.net/zwvista/article/details/18655
def setWallpaper(image_path):
    key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
    win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
    win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0")
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,image_path, 1+2)

#獲取指定目錄下所有文件名稱,參考地址https://blog.csdn.net/zhuzuwei/article/details/79925562
filePath = 'C:\\background\\'
test = os.listdir(filePath+"now\\")

#從獲取的圖片名稱列表中隨機取出一個值,設置為壁紙,隨機取值參考https://blog.csdn.net/weixin_39791387/article/details/84958436?utm_medium=distribute.pc_relevant_download.none-task-blog-baidujs-1.nonecase&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-baidujs-1.nonecase
image_path = random.choice(test)
setWallpaper(filePath+"now\\"+image_path)

#將設置好的圖片移動到其他文件夾內,參考https://blog.csdn.net/silentwolfyh/article/details/74931123
shutil.move(filePath+"now\\"+image_path, filePath+"ok\\")

print("設置成功")
    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM