#------------------------------------------------------------------------------ # # FileCopy.py # Illustrates reading from and writing to files in Python. Copies the file # named in the first command line argument to a new file named in the second # command line argument. For instance, the following line will copy the # contents of file1 into file2, which will be created if it does not exist. # # python FileCopy.py file1 file2 # # Warning: file2 will be overwitten if it already exists. # # Exercise: # Write a program that does everything this one does, but first tests whether # file2 exists, and if it does, creates a backup copy of it called file2.bak. # #------------------------------------------------------------------------------ import sys # main() ---------------------------------------------------------------------- def main(): if len(sys.argv)!=3: print("Usage:") print("python", sys.argv[0], "", "") exit() # end if fin = open(sys.argv[1]) fout = open(sys.argv[2], 'w') for line in fin: print(line[:-1], file=fout) # end for fin.close() fout.close() # end main() ------------------------------------------------------------------ # ----------------------------------------------------------------------------- if(__name__=='__main__'): main() # end if ----------------------------------------------------------------------