Looping through and renaming files is actually deleting them too. why?

Question:

I’m looping through files in a directory and changing their names to 1, 2, 3, etc. When I run it once it works fine. But if I run it again it ends up deleting a lot of the files. Can’t figure out why.

import os

pth = "path here"

lst = os.listdir(pth)
counter = 1
for fle in lst:
  new_pth = pth + "/" + fle
  final_pth = pth + "/" + str(counter) + ".svg"
  os.rename(new_pth, final_pth)
  counter += 1
Asked By: i_feel_dumb

||

Answers:

Let’s take a case where you have 13 files. The first time the script runs, it goes through the files and renames them from 1-13. The second time, it starts with file 1, renames it to file 1 (does nothing), but after that instead of going to file 2, the loop picks up file 10. File 10 then gets renamed to file 2. The third time the loop runs, it doesn’t pick up file 3, but rather, file 11, which gets renamed to file 3. It goes on renaming the file from 10 – 13 first before the loop picks up file 2.

But now, file 2 is actually file 10, and the original file 2 has been deleted. File 3 is file file 11 and the original file 3 is gone. This is why you face this problem. If you were to have only 9 files, you will notice that the problem doesn’t occur.

To fix it:

Replace your for fle in lst: loop with:

for fle in sorted(lst, key=lambda x:int(x.replace('.svg', ''))):

This will remove the .svg, look at the numbers as ints, and sort them in numerical order.

Answered By: M B
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.