1

my code so far:

import os

root = os.listdir("/path/to/dir")
pic_dir = {}
len_wallpaper = int((24 / (len(root))))

for i in range(24):
    if i<10 :
        pic_dir[(f"{0}{i}")] = root[0]
    else:
        pic_dir[i] = root[0]


print(pic_dir)

current output:

{'00': 'file_1', '01': 'file_1', '02': 'file_1', ... '23': 'file1'}

This is good so far, but what I really want is to loop through the files n times, so they will add to the list n times and then move onto the next file. So more like this:

{'00': 'file_1', '01': 'file_1', '02': 'file_1', ... 
 '07': 'file2', '08': 'file2', ... 
 '22': 'file4', '23': 'file4'}

The directory will hold pictures, and my end goal is to create some sort of dynamic wallpaper that changes based on the time.

'len_wallpaper' calculates the amount of times a file needs to be ran through this loop.

Can this be done by using a nested loop of some kind?

koko
  • 37
  • 1
  • 7
  • 1
    Not quite clear, so the `root` dir is a list of files, right ? why need nested ? – YOLO Jan 12 '20 at 11:18
  • I've edited my question a bit, I hope this makes it clearer of my end goal. – koko Jan 12 '20 at 11:30
  • 1
    I don't understand, does `int((24 / (len(root))))` in your code make any sense? – KaiserKatze Jan 12 '20 at 11:40
  • It calculates the amount of times a file should be added to the dictionary. E.g if there is 4 files, then one file should be added 6 times to the list. However, it is not currently being used in this code. – koko Jan 12 '20 at 11:41
  • 1
    so it's time interval between the transitions of wallpapers. what's the unit of `24` then? minutes or seconds? – KaiserKatze Jan 12 '20 at 11:44
  • 24 would be the hours, and this is to be referred to time e.g : time_H = int(datetime.now().strftime('%H')) – koko Jan 12 '20 at 11:46
  • 1
    i think this design is flawed from the beginning, why don't you put all filenames of wallpapers into a list and loop through the list as time goes on? – KaiserKatze Jan 12 '20 at 11:52
  • yeah I think this might be easier, I'm going to rethink this. Thanks. – koko Jan 12 '20 at 11:55

4 Answers4

2

Following is just to give you an idea but essentially the design seems to be wrong as what if your number of files exceeds 24?

counter = 0
for i in range(24):
    if len(str(i)) == 1:
        pic_dir[(f"{0}{i}")] = root[counter]
    else:
        pic_dir[i] = root[counter]
    counter += 1
    if counter > len_wallpaper - 1: 
        counter = 0

UzairTariq
  • 51
  • 3
2

if you are trying to add the file names len_wallpaper times to the dictionary its easy (if thats what you are trying to achieve)

import os

root = os.listdir("/path/to/directory")
pic_dir = {}
len_wallpaper = int(24/len(root))
count=0
for i in range(24):
    print(root[i])
    for j in range(len_wallpaper):
        print(j)
        if count<10 :
            pic_dir[(f"{0}{count}")] = root[i]
        else :
            pic_dir[f"{count}"] = root[i]
        count+=1



print(pic_dir)

2

Your problem is an X-Y problem. You can show your wallpaper images in a simpler way, using a list or, better, an itertools.cycle object.

Put comments in the source code, use as meaningful names as you are able to find...

import os, itertools

# read the filenames of images, count them,  put them in a cycle object
images = os.listdir("/path/to/dir")
n_images = len(images)
images = itertools.cycle(images)

# determine how long, in seconds, a single image will stay on screen
# so that we show all images in 24h
duration = (24*60*60)/n_images 

# IMPORTANT we use a cycle object, the loop body is executed forever or,
# at least, until the program is stopped
for image in images:
    # write yourself wallpaperize & waitseconds 
    wallpaperize(image)
    waitseconds(duration)
gboffi
  • 22,939
  • 8
  • 54
  • 85
1

Considering that your design to achieve the goal is kinda flawed, I proposed to implement it in a way that a function put all paths of image files of wallpapers into a single list and traverse the list as time goes on, as is shown below:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import itertools
from threading import Timer

# put more image file extensions here if you want
VALID_IMAGE_EXTENSIONS = [".png", ".jpg", ".jpeg"]

DIRECTORY_WALLPAPERS = "/path/to/dir"

def FileFilterForImages(entry: str) -> bool:
    filename, extension = os.path.splittext(entry)
    extension = extension.lower() # sometimes extension names are made up of capital characters
    return extension in VALID_IMAGE_EXTENSIONS

def FindAllWallpapers(path: str) -> list:
    list_of_image_files = []
    for rootdir, dirs, files in os.walk(path): # walks through the entire tree below specific directory
        for file in files:
            if FileFilterForImages(file):
                list_of_image_files.append(file)
    # according to @gboffi[user:2749397], i replace the list with iterator :)
    return list_of_image_files

def DisplayWallpaper(path: str):
    pass # TODO to be implemented
    # i'm curious about how to change wallpapers on Windows with python
    # so i googled a little
    # @see: https://stackoverflow.com/questions/1977694/how-can-i-change-my-desktop-background-with-python

def GetWallpaperIterator():
    list_of_image_files = FindAllWallpapers(DIRECTORY_WALLPAPERS)
    return itertools.cycle(list_of_image_files)

def OnTimer():
    for image_file_path in GetWallpaperIterator():
        DisplayWallpaper(image_file_path)

if __name__ == "__main__":
    image_files = FindAllWallpapers(DIRECTORY_WALLPAPERS)
    time_interval_for_each_wallpaper = 60 # seconds
    # this means each wallpaper will stay on screen
    # for 60 seconds before getting changed

    # [Timer Object](https://docs.python.org/3.9/library/threading.html#timer-objects)
    # use threading.Timer instead of time.sleep
    timer = Timer(interval=time_interval_for_each_wallpaper, function=OnTimer)
    timer.start() # start the automaton !!!
KaiserKatze
  • 1,521
  • 2
  • 20
  • 30