Question: I have the code: import random import os # Get list of images in folder folder = C:UsersdanieMusicNumber Assignment Test files = os.listdir(folder) #

I have the code:

 

import random
import os

# Get list of images in folder
folder = "C:\Users\danie\Music\Number Assignment Test""
files = os.listdir(folder)

# Generate random numbers
rand1 = random.randrange(1, 21)
rand2 = random.randrange(1, 11)
rand3 = random.randrange(1, 9)
rand4 = random.randrange(1, 7)
rand5 = random.randrange(1, 7)

# Loop through each image
for file in files:
   # Get file name and extension
   base_name = os.path.splitext(file)[0]
   ext = os.path.splitext(file)[1]
   # Create new file name
   new_name = base_name + "(" + str(rand1) + "," + str(rand2) + "," + str(rand3) + "," + str(rand4) + "," + str(rand5) + ")" + ext
   # Rename file
   os.rename(os.path.join(folder, file), os.path.join(folder, new_name))

 

But when I run it I just get:

 

Traceback (most recent call last):
 File "", line 1, in
NameError: name 'files' is not defined. Did you mean: 'filter'?

 

How can I fix this?

 

For reference, I'm trying to get the randomly generated numbers to get added to the file names as a suffix.

Any help on this would be greatly appreciated!

P.s. This is in python 3

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

The error message youre encountering is indicating that the name files is not defined when y... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!