Suppose I have a set
of file rename operations:
renames={(current_1,new_1),(current_2,new_2),...}
It is guaranteed that the files current_1,current_2,...
exist and that the new files new_1,new_2,...
are unique.
All files are instances of pathlib.Path
.
They may be, however, files that are currently named as another file has to be renamed: i.e. it may exist an instance of current_i==new_j
.
What would be an elegant way to implement the rename operations? Note that I can't just iterate over renames
and rename each file, because I have to be prepared for a situation where the new name conflicts with the name of a file yet to be renamed.
I'm specifically looking for an implementation in Python3, and I would like renames to be kept a set
in the form above.
A simple way is to temporarily prefix the files:
temporal_prefix="a big string guaranteed not to appear in file names"
for current,new in renames:
current.rename(current.with_name(temporal_prefix+current.name))
for current,new in renames:
current.with_name(temporal_prefix+current.name).rename(new)
But this is not very elegant and it requires up to double the needed file operations. And finding a good prefix may be a problem in and of itself. Is it possible to do this in one loop, using the minimum number of file operations?