0

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

FOLDER 1:

  • 05.xml
  • 06.xml
  • 07.xml
  • 08.xml

FOLDER 2:

  • 01_2500.jpeg
  • 02_2501.jpeg
  • 03_2502.jpeg
  • 04_2503.jpeg
  • 05_2504.jpeg
  • 06_2505.jpeg
  • 07_2506.jpeg
  • 08_2507.jpeg

I need to rename the folder 1 as follows:

  • 2504.xml
  • 2505.xml
  • 2506.xml
  • 2507.xml

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.

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.