This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: Support the same files with new param in shutil.copyfile
Type: enhancement Stage: patch review
Components: Library (Lib) Versions: Python 3.10
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: milanbalazs, serhiy.storchaka
Priority: normal Keywords: patch

Created on 2021-02-08 17:32 by milanbalazs, last changed 2022-04-11 14:59 by admin.

Pull Requests
URL Status Linked Edit
PR 24482 open milanbalazs, 2021-02-08 18:03
Messages (4)
msg386634 - (view) Author: Milan Balazs (milanbalazs) * Date: 2021-02-08 17:32
The "shutil.copyfile" raises a "SameFileError" exception if the src and dts files are the same.

There is no option to allow the same files(like in case of shutil.copytree(dirs_exist_ok=False)).

For example:

import shutil

shutil.copyfile("test.txt", "test.txt")


>>> python3 
Traceback (most recent call last):
  File "", line 3, in <module>
    shutil.copyfile("test.txt", "test.txt")
  File "/usr/lib/python3.6/", line 104, in copyfile
    raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
shutil.SameFileError: 'test.txt' and 'test.txt' are the same file
msg386639 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2021-02-08 18:12
You can use try/except.

    shutil.copyfile("test.txt", "test.txt")
except SameFileError:
msg386641 - (view) Author: Milan Balazs (milanbalazs) * Date: 2021-02-08 18:18
Sure, you can use try/except but it would be nice if the "shutil.copyfile" function supports the same files.

If I have many files (more thousand), I don't want to check them with a try/except.

Furthermore if I want to cover the unexpected exceptions as well I need to use nested try/except (I guess it's not the most elegant way).


    shutil.copyfile("test.txt", "test.txt")
except SameFileError:
except Exception as unexpected_exception:
    raise unexpected_exception
msg388998 - (view) Author: Milan Balazs (milanbalazs) * Date: 2021-03-18 08:31
Could you somebody review the PR for this ticket, please?
Date User Action Args
2022-04-11 14:59:41adminsetgithub: 87331
2021-03-18 08:31:52milanbalazssetmessages: + msg388998
2021-02-08 18:18:32milanbalazssetmessages: + msg386641
2021-02-08 18:12:07serhiy.storchakasetnosy: + serhiy.storchaka
messages: + msg386639
2021-02-08 18:03:16milanbalazssetkeywords: + patch
stage: patch review
pull_requests: + pull_request23274
2021-02-08 17:32:01milanbalazscreate