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

dn via Python-list <[email protected]>
Newsgroups gmane.comp.python.general
Organization DWM
Message-ID <[email protected]>
The suggestion (below) is good-practice. However, it's advanced-Python 
compared to the OP's first-course progress.

What is disappointing, is that instead of general strings as file-names 
the class has not been introduced to pathlib 
(https://docs.python.org/3/library/pathlib.html).

PS Ethan: way-down the docs you'll find two very handy methods worth 
applying as a second-attempt at this challenge!



On 28/08/25 03:41, Chris Angelico via Python-list 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.
> 
> I would strongly recommend combining the two opens into a single with
> statement. If you can guarantee a minimum Python version of 3.10
> (released 2020, now in source-only-fix mode, so any fully supported
> version will indeed be >=3.10), you can write it like this:
> 
> with (open(s) as src,
>      open(d, "w") as dst):
> 
> or this:
> 
> with (
>      open(s) as src,
>      open(d, "w") as dst,
> ):
> 
> If you need to support older versions of Python, this would need to be
> done with backslashes, which is ugly, but still better (IMO) than
> using two nested context managers.
> 
> Out of curiosity, why do you have argc and argv? Seems a bit
> unnecessary. Python isn't C.
> 
> ChrisA

-- 
Regards,
=dn
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.