file - I need to write a Python script to sort pictures, how would I do this? -


what i'm looking script can go through huge list of pictures , sort them folders.

so take pictures of dogs @ shows, lets take several pictures of dog1, dogs picture automatically named in serial number format (dog1-1, dog1-2, dog1-3, etc). dog2 follow same format.

i'd script can take dog1-1-10 , move them folder named dog 1. dog2-1-10 folder named dog 2, etc.

how can done in python?

so basically, want is:

  1. find every file in given folder
  2. take first part of each filename , use folder name
  3. if folder doesn't exist, create it
  4. move file folder
  5. repeat

well, nifty! figuring out want half battle -- now, it's matter of googling , turning code.

first, need folder check in:

folder_path = "myfolder" 

now, want find every file inside folder. quick googling session turns this:

import os import os.path  images = [f f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))] 

as aside, i'm going using os.path.join fair bit, may want briefly read on does. guide linked in comments covers well.

now, want first part of each name. i'm going assume we'll treat first dash folder name, , ignore rest. 1 way use string.split, splits string given character list of strings, , grab first element:

for image in images:     folder_name = image.split('-')[0] 

now, if folder doesn't exist, want create it. again, google our friend:

new_path = os.path.join(folder_path, folder_name) if not os.path.exists(new_path):     os.makedirs(new_path) 

and finally, move original image:

import shutil  old_image_path = os.path.join(folder_path, image) new_image_path = os.path.join(new_path, image) shutil.move(old_image_path, new_image_path) 

putting together:

import os import os.path import shutil  folder_path = "test"  images = [f f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]  image in images:     folder_name = image.split('-')[0]      new_path = os.path.join(folder_path, folder_name)     if not os.path.exists(new_path):         os.makedirs(new_path)      old_image_path = os.path.join(folder_path, image)     new_image_path = os.path.join(new_path, image)     shutil.move(old_image_path, new_image_path) 

Comments

Popular posts from this blog

jQuery Mobile app not scrolling in Firefox -

c++ - How to add Crypto++ library to Qt project -

php array slice every 2th rule -