0

I have a folder which has a list of files. I have two dictionaries which has original filenames and new filenames.

FldName = r'C:\Users\Shei\Documents\Test'
oldFname = {'mangoes.txt', 'apple.txt', 'banana.txt'}
NewFname = {'random.txt', 'example1.txt', 'something.txt'}

I understand I can use the following to rename a single file

import os  
os.rename('Apple.txt','example1.txt') 

but I am not sure, how do I bulk rename files based on list in the dictionary.

Any help would be greatly appreciated

Py_junior
  • 93
  • 1
  • 10

2 Answers2

1

Try to zip the lists together

import os

FldName = r'C:\Users\Shei\Documents\Test'
oldFname = ['mangoes.txt', 'apple.txt', 'banana.txt']
NewFname = ['random.txt', 'example1.txt', 'something.txt']

for i, j in zip(oldFname,NewFname):
    os.rename(os.path.join(FldName,i),os.path.join(FldName,j))
0

sets are unordered, try making them lists:

FldName = r'C:\Users\Shei\Documents\Test'
oldFname = ['mangoes.txt', 'apple.txt', 'banana.txt']
NewFname = ['random.txt', 'example1.txt', 'something.txt']
for x, y in zip(oldFname, NewFname):
    os.rename(os.path.join(FldName, x), os.path.join(FldName, y))
U13-Forward
  • 69,221
  • 14
  • 89
  • 114