2017-02-07 6 views
1

MomentumDash (교육용으로 만 사용)에서 일부 이미지를 다운로드하려고합니다. 나는 다음 파이썬 코드를 작성했습니다 :다운로드 한 이미지가 항상 배경으로 설정되지 않습니까?

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) 

것은이 이미지를 설정하려면이 progrm의 확률 1/7 틱입니다.
대부분의 경우 검은 색 배경 화면을 제공합니다.
어디서 잘못 되었나요?

+0

'os.listdir()'은 주어진 디렉토리에있는 모든 파일의 목록을 제공합니다 - 작업 디렉토리에 다운로드하는 이미지 이외의 파일이 있습니까? (힌트 :이 python 스크립트) – asongtoruin

+0

먼저 'random'에 다른 변수 이름을 쓰면 라이브러리 이름을 덮어 쓰게됩니다. 둘째,'os.listdir (cwd)'에 대해 얻은 것을 출력하십시오. 일부 항목은 적절한 이미지 파일이 아닙니다. –

답변

2

다음을 시도해보십시오. 이렇게하면 jpg 개의 파일 만 제공되도록 디렉토리 목록이 필터링됩니다. 무작위로 항목을 가져옵니다. 또한 os.path.join()은 경로와 이름을 안전하게 결합하는 데 사용됩니다.

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)   

파일의 목록은 파이썬의 list comprehension 기능을 사용하여 필터링됩니다. 이것은 기존 항목에서 새 목록을 만드는 방법입니다. 이 경우 선택적인 if 문을 사용하여 새 목록의 파일 확장명이 .jpg 인 파일 만 포함시킵니다.

+0

은 확장자를 .jpg로 강요하지 않을 생각이었습니다. +1 – asongtoruin

+0

멋진 답변입니다! 이 문법을 좀더 자세히 설명해 주시겠습니까? os.path.splitext (f) [1] .lower() == ".jpg"] ' –

+1

의 경우 이미지 요청은 os.listdir (fwd)의 f에 대해 f 파이썬 언어의 대답에 링크를 추가했습니다. –

1

는 다음을 시도해보십시오

import urllib 
import os 
import random 
import ctypes 

# Set up an output folder 
out_folder = os.path.join(os.getcwd(), 'Backgrounds') 

# Make it if it doesn't exist 
if not os.path.isdir(out_folder): 
    os.mkdir(out_folder) 

# Loop through all values between 1 and 15 
for choice in range(1,15): 
    #Downloads images 
    a = urllib.urlretrieve("https://momentumdash.com/backgrounds/" + "%02d" % (choice,)+".jpg", 
          os.path.join(out_folder, "{}.jpg".format(choice)) 
          ) 

selected_wallpaper = random.choice(os.listdir(out_folder)) 

#Making the image to desktop image 
SPI_SETDESKWALLPAPER = 20 
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, os.path.join(out_folder, selected_wallpaper), 3) 

이, 당신의 현재 작업 디렉토리에 Backgrounds라는 폴더를 만들고 거기에 모든 이미지를 저장 한 다음 무작위로 하나를 선택합니다.

+0

절대 새 폴더 만들기를 생각하지 마십시오! –