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?
The problem can be illustrated easily. You have following files:
and you are going to rename them:
However, as soon as you want to rename
b.txt
toa.txt
there is the reported problem because the filea.txt
already exists there.You can implement the procedure in two passes:
If the set of temporary names don't collide with the original names the procedure is safe.