1

In general, os.rename requires two inputs, the 'original' and the 'new' filename.

Parameters: source: A path-like object representing the file system path. This is the source file path which is to renamed. destination: A path-like object representing the file system path. src_dir_fd (optional): A file descriptor referring to a directory. dst_dir_fd (optional): A file descriptor referring to a directory.

Return Type: This method does not return any value.

So, what happens in the following scenario?

os.rename(original, original)

And, is there any harm if this were to operate over a large number of files?

Patrick
  • 13
  • 2
  • 1
    On POSIX systems, assuming that the `rename(2)` system call is being used, this is safe: "If oldpath and newpath are existing hard links referring to the same file, then rename() does nothing, and returns a success status." – Thomas Oct 26 '21 at 17:59
  • Currently using Python in Windows as the underlying system, accessing a NAS drive. – Patrick Oct 26 '21 at 18:01
  • 2
    Have you tried making an empty test file and running the command? If not, do it. If so, tell what happened. – Mad Physicist Oct 26 '21 at 18:02
  • I've run it on a folder full of files. The script successfully renames intended files, but I didn't use an IF or switch to filter out cases when 'original' == 'original'. And, I can't see that anything happened. But I also didn't think it wise to unnecessarily rename every file if it was actually going to do it. Since there is no function return, I didn't know what Python would attempt. – Patrick Oct 26 '21 at 18:06
  • What harm do you expect? Do you think the "renamed" files will be screwed up, or is it just wasted time you're worried about? Either way, it's quite easy to write a test: for the former case, create many files, try to rename them all to their original name, and see if the contents are changed after the operation. For the latter, just compare the difference in time when you try to rename everything to its original name and a new name. – Pranav Hosangadi Oct 26 '21 at 18:16
  • On Windows, it defers to [MoveFileExW](https://github.com/python/cpython/blob/main/Modules/posixmodule.c#L4674). [Docs](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw) do not specify any special behavior when source is the same as destination – Marat Oct 26 '21 at 18:16
  • 1
    I didn't expect contents of the files being harmed, I was wondering if it was causing a filename to be 'rewritten' and thus needless disk writes (life of disk). And a potential application speed sink if extended to a drive with large numbers of files. – Patrick Oct 26 '21 at 18:27
  • 1
    Monitoring an empty file (as suggested by Mad Physicist), and looking at file properties, changing the filename will update the 'time' a file was accessed, but when name is not changed because of equal inputs, the accessed time does not update. – Patrick Oct 26 '21 at 18:29

0 Answers0