Rename files in folder using values in list in python

Viewed 7

I have a list containing new names.

wo = ['ab','cd','ef','gh']

I have 4 files in a folder.

path = 'C:/Users/myname/Desktop/SM'

Now I need to rename as first value in the list for first file in the folder.

I tried,

import os
path = 'C:/Users/myname/Desktop/SM'
files = sorted(os.listdir(path))
wo = ['1','2','3','4','5','6','7','8','9','10'] # Text to be added at the end of the file

for index, file in enumerate(files):
    os.rename(os.path.join(path, file), os.path.join(path, ''.join([files[index].split('.xlsx')[0] + '-' + wo[index], '.xlsx'])))

Here, the file new names are mismatching. For example, first value in the list is used to rename 3rd file in the folder. So the problem is order is changing after reading files in folder.

Is there any way to rename files without changing order?

0 Answers
Related