Q:

Index error for list in python

I've written the following code to iterate through folders and their files and to rename each file in each folder as the file's index in the folder. E.g The first file in each folder will be named 1.JPG, the second 2.JPG and so on. The folder names are integers from 1 to 82. I need the folder name to specify the path in os.rename() and was planning to obtain it from the dirs list because os.walk(path) does not traverse the directories in order.
Code:
import os
import sys

path='/home/srilatha/Desktop/Research_intern/Data_sets/Final'
i=0

for root, dirs, files in os.walk(path):
    print(dirs)
    print(dirs[i])
    #folder_name=dirs[0]
    #print(folder_name)
    j=0
    for name in sorted(files):
        j+=1
        #print('j=')
        #print(j)
        print(name)
        new=str(j)
        new_name=new+'.JPG'
        print(new_name)
        #os.rename(name,new_name)

    i+=1

Error Message:
/usr/bin/python3.4 /home/srilatha/PycharmProjects/Research_Intern/Sort_images_into_folders.py
['9', '43', '78', '7', '51', '15', '4', '68', '48', '67', '27', '16', '55', '20', '57', '38', '47', '18', '77', '82', '12', '65', '25', '59', '49', '30', '36', '79', '71', '17', '22', '42', '40', '73', '19', '24', '10', '37', '32', '3', '64', '62', '58', '13', '72', '2', '14', '70', '11', '66', '69', '50', '54', '34', '5', '52', '81', '26', '39', '60', '1', '56', '33', '80', '23', '53', '44', '45', '29', '41', '28', '35', '6', '46', '31', '8', '63', '75', '61', '76', '74', '21']
9
[]
Traceback (most recent call last):
  File "/home/srilatha/PycharmProjects/Research_Intern/Sort_images_into_folders.py", line 9, in <module>
    print(dirs[i])
IndexError: list index out of range

A:

I assume you want something like this?
# Import the os module, for the os.walk function
import os

# Set the directory you want to start from
rootDir = '/Users/heinst'
for dirName, subdirList, fileList in os.walk(rootDir):
    print('Found directory: %s' % dirName)
    i = 0
    for fname in fileList:
        print '\t{0} -> {1}'.format(fname, str(i) + os.path.splitext(fname)[1])
        i += 1

