Becca
Becca

Reputation: 69

converting a string into a file name

I am new to programming. I have to write a function that ultimately loads a series of images. It takes user input of the beginning of the file name and how many files there are, then I create a loop that loads all the images and stores them in a list. An example: file names are da_1.gif, da_2.gif, da_3.gif. User input would be image= da, n= 3. In my loop, I have updated the image variable to create the correct name of the file, but when I run the program it comes back with an error that the file name doesn't exist. The file is saved in the same folder as my code file, so I am assuming the error is that it is not reading the string as a file name. How do I create a code that will successfully load the images?

Here is my code:

def loadImages():
  images= []
  image= input("Enter the abbreviation that describes the subject of the photograph:")
  n= int(input("Enter the number of images you want to load:"))
  if n >= 3 and n <= 16:
    for i in range (1, n+1):
      width= getWidth() * i
      height= 0
      i= str(i)
      image= image + "_" + i + ".gif"
      image_2= loadImage(image)
      drawImage(image, width, height)
      images.append(image)

Upvotes: 1

Views: 474

Answers (1)

mnistic
mnistic

Reputation: 11010

With image = image + "_" + i + ".gif" you are re-assigning the image variable, but it doesn't look like that was your intent. You want image to hold the abbreviation so that the file name can be constructed from it. Also, you probably don't want to pass the file path to drawImage, but the image object instead. To fix, simply use a temp variable:

  image_path = image + "_" + i + ".gif"
  image_2= loadImage(image_path)
  drawImage(image_2, width, height)
  images.append(image_2)

Upvotes: 2

Related Questions