TAGS :Viewed: 91 - Published at: a few seconds ago

[ PYTHON: Searching for a file name from an array and then relocating the file ]

I'm new to Python and could really use some help. I have a large collection of images that I'm sorting. I need every 260th image (for example: 0, 260, 520, 780, etc). I then need to relocate those images to a new folder. Here is my code so far:

import os, os.path, sys, shutil
root = '.'
dst = "/Users/Desktop"

print "/////// F I N D__A L L__F I L E S __W I T H I N __R A N G E ///////////////////"

selectPhotos = range(260, 213921)
print selectPhotos[::260]

print "/////// L I S T__O F __A L L __J P E G S ///////////////////"

for files in os.listdir("/Users/Desktop/spaceOddy/"):
   #if files.endswith(".jpg"):
     # print files

   if files.startswith(selectPhotos[]):
      print files

      shutil.move ("files", root)

My code isn't working in two places.

  1. I receive an error that I need to pass a tuple into startswith, which I don't know how to do. I know what a tuple is but in terms of syntax I'm in the dark.

  2. I don't know much about shutil.move. If anyone knows of a better approach I'd appreciate it.


Answer 1

To move every nth image file in a directory to another directory:

#!/usr/bin/env python
from __future__ import print_function
import glob
import shutil
import sys

dstdir = "/Users/Desktop"
for file in glob.glob("/Users/Desktop/spaceOddy/*.jpg")[::260]:
        shutil.move(file, dstdir)
    except EnvironmentError as e:
        print("can't move {}, error {}".format(file, e), file=sys.stderr)

Answer 2

Start here.

import os, shutil
root = '.'
src = "/Users/Desktop/spaceOddy/"
dst = "/Users/Desktop"

for i, filename in enumerate(os.listdir(src)):

    if i%260 == 0:
      print filename
      shutil.move (src + filename, root)
  • I've changed files to filename. Inside the loop, filename is a string: the name of single file in the directory.

  • I used enumerate, which gives us both the name of a file and a counter starting at 0. Try something like print enumerate(['cat', 'dog', 'pig']) in a shell to see what it does.

  • Now that we have a counter, I used the test i%260 == 0 to choose only ever 260th file.

  • If you need to get every 260th .jpg file, change the if statement to if i%260==0 and filename.endswith('.jpg')

  • I don't know what you were trying to do with startswith, but you need to pass it a string as an argument if you want to use it, not a tuple.

  • print selectPhotos[::260] doesn't actually change selectPhotos. You may not actually need it in this case, but for the future... you can pass a step value to range like this selectPhotos = range(0,213921,260) or to change selectPhotos after creating it, use selectPhotos = selectPhotos[::260]