Path: csiph.com!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Ethan Carter Newsgroups: comp.lang.python Subject: can you improve this text-only beginner copy program? Date: Wed, 27 Aug 2025 11:03:22 -0300 Organization: A noiseless patient Spider Lines: 34 Message-ID: <87a53kdfpx.fsf@somewhere.edu> MIME-Version: 1.0 Content-Type: text/plain Injection-Date: Wed, 27 Aug 2025 14:03:23 +0000 (UTC) Injection-Info: dont-email.me; posting-host="1ae1a19ff8f9677ec29754ac355e2a6e"; logging-data="764107"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19gthTe6086JmEeQaCrfDiiUK3PtLL10MU=" Cancel-Lock: sha1:V1djc48j1hqdVnq3iEWahv0F8tQ= sha1:aEO6P6Jj9+7lUy7vVj6K/+WMGA0= Xref: csiph.com comp.lang.python:197540 The program below only copies text files on purpose---because we haven't learned about binary files in this course yet. (So I could catch a UnicodeDecodeError while writing.) If an exception is raised while writing, I need to delete the file that was created. Can you think of anything I'm missing? I'm sure you can improve it by making it more efficient for not reading the entire file into memory---I'm aware of that, but also not going in that direction right now. (I will worry about that when I write a new version that does binary reading.) In summary, don't demand too much of a Python beginner here. Thanks! # -*- mode: python; python-indent-offset: 2 -*- import os import sys 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 def usage(program): return f"""usage: python {program} source.txt destination.txt""" def main(argc, argv): if argc != 3: raise SystemExit(usage(argv[0])) copy(argv[1], argv[2]) if __name__ == "__main__": main(len(sys.argv), sys.argv)