0

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
  • Maybe the `os.listdir(pth)` is not given the same order in each call when list all the files. So the first time all fine, but the second run the `2.svg` file maybe is taking the name `1.svg` and so on if you follow this files are being deleting renaming it. – StandardIO Oct 23 '22 at 04:41

1 Answers1

2

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.

M B
  • 2,700
  • 2
  • 15
  • 20
  • Ah okay so then it doesn't necessarily iterate in order over the files? The list of the files is not necessarily ordered "properly"? – i_feel_dumb Oct 23 '22 at 04:45
  • @i_feel_dumb Exactly, I have added the way to fix the issue, inspired from answers to [this question](https://stackoverflow.com/q/4813061/3730626) – M B Oct 23 '22 at 04:46