0

I have a bunch of images that have filenames that represent a range of values that I need to split into individual images. For example, for an image with the filename 1000-1200.jpg, I need 200 individual copies of the image named 1000.jpg, 1001.jpg, 1002.jpg, etc.

I know a bit of python but any suggestions on the quickest way to go about this would be much appreciated.

EDIT: Here's what I have so far. The only issue is that it strips leading zeros from the filename and I'm not quite sure how to fix that.

import os
from shutil import copyfile

fileList = []
filePath = 'C:\\AD\\Scripts\\to_split'

for file in os.listdir(filePath):
    if file.endswith(".jpg"):
        fileList.append(file)

for file in fileList:
    fileName = os.path.splitext(file)[0].split("-")
    rangeStart = fileName[0]
    rangeEnd = fileName[1]
    for part in range(int(rangeStart), int(rangeEnd)+1):
        copyfile(os.path.join(filePath, file), os.path.join(filePath, str(part) + ".jpg"))
amblerd99
  • 3
  • 3
  • Hi there, and welcome to Stack Overflow. Please show us any code you have tried thus far, along with what hasn't worked (error message, stack trace, faulty result, etc.). If you haven't tried *anything*, that's OK, but it would probably be best to go read up on things like "how to read the names of files in a folder in python" and "how to make a copy of a file in python", make an attempt on your own, and *come back to Stack Overflow* with a specific problem and piece of code you're stuck on :) – MyStackRunnethOver Nov 28 '18 at 00:28
  • 1
    Yeah, it was a bit of a panicked question TBH. I'll get to work and report back, thanks for being polite :D – amblerd99 Nov 28 '18 at 00:57
  • Great :) and no problem. Remember: politeness is what you should expect here. It's in [The Code of Conduct](https://stackoverflow.com/conduct), and everyone should both give and get it – MyStackRunnethOver Nov 28 '18 at 01:01

1 Answers1

0

Lets break the problem down:

Step 1. Get all files in folder

Step 2. for each file, Get string from filename

Step 3. split the string into two ints a and b with str.split("-")

Step 4. for x in range(a, b), copy file and set the name of the file as str(x)

Jeff
  • 810
  • 8
  • 18
  • Thanks for that Jeff, that was really helpful. Any idea how I can restore the leading zeros in the filenames that get lost when they're converted to integers? – amblerd99 Nov 28 '18 at 02:26
  • the easiest way is to store both the original string and the parsed integer. the second way would be to pad the 0's, provided you knew how many places you need. https://askubuntu.com/questions/503530/how-do-i-add-zero-padding-to-filenames-that-already-have-numbers-in-them – Jeff Nov 28 '18 at 18:30