Rose
Rose

Reputation: 3

Why do I get IndexError: List index out of range when turning images into CSV file?

I am trying to turn images into a CSV file. When running the script, I obtain the error: IndexError: list index out of range. Can someone help me solve this error?

import sys

import os

import csv

import glob



SPLIT_CHAR = '\\'

MAX_IMG_PER_CLASS = 5000000



# Path to input directory; subdir  conatain test  image files and name of subdir matches class name

path = sys.argv[1]



directories = [x[0] for x in os.walk(path)]



data = []



for directory in directories:

    tag = directory.rsplit(SPLIT_CHAR, 1)[-1]

    images = glob.glob(directory + "/*.jpg")



    if len(images) > 0:

        img_Cnt = 0

        for image in images:

            if img_Cnt <= MAX_IMG_PER_CLASS:

              taggedImage = [image, tag]

              data.append(taggedImage)

              print(taggedImage)

              img_Cnt += 1

            else:

              print("Got {0} images, breaking".format(img_Cnt))

              break



with open("images.csv", "w") as file:

    writer = csv.writer(file)

    writer.writerows(data)

input("All done. Press any key...")

runfile('C:/Users/otr/Documents/Python Scripts/csvfile.py', wdir='C:/Users/otr/Documents/Python Scripts')

The traceback is:

Traceback (most recent call last):

  File "<ipython-input-7-bec6ed956596>", line 1, in <module>
    runfile('C:/Users/otr/Documents/Python Scripts/csvfile.py', wdir='C:/Users/otr/Documents/Python Scripts')

  File "C:\Users\otr\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\otr\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/otr/Documents/Python Scripts/csvfile.py", line 26, in <module>
    path = sys.argv[1]

IndexError: list index out of range

Upvotes: 0

Views: 66

Answers (1)

hajduzs
hajduzs

Reputation: 83

Looks like your list containing command line arguments (sys.argv) doesn't contain anything else but the name of the script at index 0.

I quickly googled and found some information here.

"sys.argv is a list in Python, which contains the command-line arguments passed to the script. "

So I suppose no arguments are passed to your script. Make sure to call the script from CLI with the path as a parameter, or hard-code the path into your script like

path = './images' #or your path 

Upvotes: 1

Related Questions