Advertisement
DeaD_EyE

get random pictures, save the state

Mar 4th, 2019
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | None | 0 0
  1. from pathlib import Path
  2. from random import choice
  3. import pickle
  4.  
  5.  
  6. def load_state():
  7.     state_file = Path('state.json')
  8.     if not state_file.exists():
  9.         pictures = list(Path('.').glob('**/*.jpg'))
  10.         save_state(pictures)
  11.         return pictures
  12.     else:
  13.         with state_file.open('rb') as fd:
  14.             return pickle.load(fd)
  15.  
  16.  
  17. def save_state(pictures):
  18.     state_file = Path('state.json')
  19.     with state_file.open('wb') as fd:
  20.         pickle.dump(pictures, fd)
  21.  
  22.  
  23. def pop_random_picture(pictures):
  24.     """
  25.    This function mutates pictures.
  26.    It returns a random picture from the set
  27.    and removes this picture from the set.
  28.    """
  29.     if pictures:
  30.         picture = choice(pictures)
  31.         pictures.remove(picture)
  32.         return picture
  33.     return None
  34.  
  35.  
  36. pictures = load_state()
  37. print(f'Number of pics: {len(pictures)}')
  38. print(pop_random_picture(pictures))
  39. save_state(pictures)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement