Skip to content

Confusing error message when rename target is an open file #129230

@jontwo

Description

@jontwo

Bug report

Bug description:

Background

Writing a tool to update and rename some files, I made a mistake and tried to rename a file while it was still open. This works on Linux, but raises an error when writing to a Windows network shares. This is known and documented - see Path.rename docs.

The issue

The problem I have is that the error message is incorrect. It says "FileNotFound", which is confusing because the files do exist. If I had got a more useful message, I would have worked out what the problem was with my tool much sooner.

Repro case

    file1 = Path("test1.txt")
    file2 = Path("test2.txt")
    file1.open("w").write("file 1 text\n")
    file2.open("w").write("file 2 text\n")
    with file1.open():
        file2.rename(file1)

Outcomes;
On linux, writing to pwd or a linux network share, file is rewritten without error.
On linux, writing to a Windows network share, an incorrect error message is given.

$ python test.py
Traceback (most recent call last):
  File "/home/jontwo/test.py", line 17, in <module>
    main()
  File "/home/jontwo/test.py", line 13, in main
    file2.rename(file1)
  File "/usr/lib/python3.12/pathlib.py", line 1363, in rename
    os.rename(self, target)
FileNotFoundError: [Errno 2] No such file or directory: 'test2.txt' -> 'test1.txt'

On Windows, writing to pwd, a useful error message is given.

c:\temp>python test.py
Traceback (most recent call last):
  File "c:\temp\test.py", line 16, in <module>
    main()
  File "c:\temp\test.py", line 12, in main
    file2.rename(file1)
  File "C:\OSGeo4W\apps\Python312\Lib\pathlib.py", line 1363, in rename
    os.rename(self, target)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'test2.txt' -> 'test1.txt'

CPython versions tested on:

3.12

Operating systems tested on:

Linux, Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-pathlibtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions