Re: can you improve this text-only beginner copy program?

MRAB <[email protected]>
Newsgroups gmane.comp.python.general
Message-ID <[email protected]>
On 2025-08-28 03:08, Grant Edwards via Python-list wrote:
> On 2025-08-27, Chris Angelico via Python-list <[email protected]> wrote:
>> On Thu, 28 Aug 2025 at 01:28, Ethan Carter <[email protected]> wrote:
>>> def copy(s, d):
>>>   """Copies text file named S to text file named D."""
>>>   with open(s) as src:
>>>     with open(d, "w") as dst:
>>>       try:
>>>         dst.write(src.read())
>>>       except Exception:
>>>         os.remove(d)
>>>         raise
>>>
>>
>> In the event of an exception, you attempt to remove the destination
>> file BEFORE exiting the `with` statement. While that might succeed on
>> some platforms, it will potentially fail on others.
> 
> Specifically, it should work on Unix/Linux OSes. I _think_ it will
> fail on (most) Windows OSes, but making definitive statements about
> how things work on "Windows" is beyond my ken.
> 
Windows won't let you delete an open file.
If an OS did let you delete an open file, how would you expect it to 
behave? Would you still be able to use the file? Would the file be 
marked for deletion and be deleted when it was finally closed?

The Zen of Python says:

In the face of ambiguity, refuse the temptation to guess.

So, close it before attempting to delete it.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.