Maria Belen
Maria Belen

Reputation: 13

Rename files with given names in python

[PYTHON] Hi everyone, I have a problem to solve. I have two folders like this

FOLDER 1:

FOLDER 2:

I need to rename the folder 1 as follows:

How can I do it? I have been trying this for days. Obviously this is a simplified example, because there are actually thousands of files to rename.

I thought that I could use split function for the folder 2 and then apply if, but I can't.

Upvotes: 0

Views: 63

Answers (1)

Ajax1234
Ajax1234

Reputation: 71451

You can create a lookup from the files in folder 2, and then apply os.rename by iterating over the contents of folder 1. The dictionary created from files in folder store store the leading digit as its key, and the trailing four digit run as a value:

import os, re
renames = dict(re.findall('\d+', i) for i in os.listdir('/folder2'))
for i in os.listdir('/folder1'):
   os.rename(i, re.sub('\d+(?=\.xml)', lambda x:renames[x.group()], i)

Upvotes: 2

Related Questions