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)
-- 
https://mail.python.org/mailman3//lists/python-list.python.org

Reply via email to