Re: can you improve this text-only beginner copy program?
Chris Angelico via Python-list <[email protected]>
| Newsgroups | gmane.comp.python.general |
|---|---|
| Message-ID | <CAPTjJmoH31CqeFY1Xg2RLkY4pLj4pvzq02=m=pLxekZOREE8BQ@mail.gmail.com> |
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