Randomly swapping file names in Python

2.3k Views Asked by At

I need to swap the names of all the files in a folder but each file has to have it's own unique name.

I tried to loop through the folder adding all the files to a list and then shuffling that list with random.shuffle(), and then looping through the folder again but this time renaming each file by order to the shuffled list.

It was something like this:

for file in os.listdir("images/"):
    os.rename(file, files_shuffle[i])
    i += 1

But I get WinError 183 "Cannot create a file when that file already exists". What would be the best way to approach this problem?

2

There are 2 best solutions below

0
On

The problem can be illustrated easily. You have following files:

a.txt
b.txt

and you are going to rename them:

b.txt -> a.txt
a.txt -> b.txt

However, as soon as you want to rename b.txt to a.txt there is the reported problem because the file a.txt already exists there.

You can implement the procedure in two passes:

  1. Rename all files to some unique names such as very long numbers.
  2. Rename these files to final (shuffled) names.

If the set of temporary names don't collide with the original names the procedure is safe.

0
On

The way to do this is by renaming them in two steps:

a --> 1 b --> 2

1 --> b 2 --> a

I randomly renamed video files with the following code:

    import os
    import random

    randlist = random.sample(range(14), 14)

    os.rename("clip0.mp4", "video0.mp4")
    os.rename("clip1.mp4", "video1.mp4")
    os.rename("clip2.mp4", "video2.mp4")
    os.rename("clip3.mp4", "video3.mp4")
    os.rename("clip4.mp4", "video4.mp4")
    os.rename("clip5.mp4", "video5.mp4")
    os.rename("clip6.mp4", "video6.mp4")
    os.rename("clip7.mp4", "video7.mp4")
    os.rename("clip8.mp4", "video8.mp4")
    os.rename("clip9.mp4", "video9.mp4")
    os.rename("clip10.mp4", "video10.mp4")
    os.rename("clip11.mp4", "video11.mp4")
    os.rename("clip12.mp4", "video12.mp4")
    os.rename("clip13.mp4", "video13.mp4")


    os.rename("video0.mp4", "clip" + str(randlist[0]) + ".mp4")
    os.rename("video1.mp4", "clip" + str(randlist[1]) + ".mp4")
    os.rename("video2.mp4", "clip" + str(randlist[2]) + ".mp4")
    os.rename("video3.mp4", "clip" + str(randlist[3]) + ".mp4")
    os.rename("video4.mp4", "clip" + str(randlist[4]) + ".mp4")
    os.rename("video5.mp4", "clip" + str(randlist[5]) + ".mp4")
    os.rename("video6.mp4", "clip" + str(randlist[6]) + ".mp4")
    os.rename("video7.mp4", "clip" + str(randlist[7]) + ".mp4")
    os.rename("video8.mp4", "clip" + str(randlist[8]) + ".mp4")
    os.rename("video9.mp4", "clip" + str(randlist[9]) + ".mp4")
    os.rename("video10.mp4", "clip" + str(randlist[10]) + ".mp4")
    os.rename("video11.mp4", "clip" + str(randlist[11]) + ".mp4")
    os.rename("video12.mp4", "clip" + str(randlist[12]) + ".mp4")
    os.rename("video13.mp4", "clip" + str(randlist[13]) + ".mp4")