TandyRayes
TandyRayes

Reputation: 65

Write a very basic copy from one file into another using command line arguments

I am new to python and trying to make a basic copy one file into another file program. My code right now is

import sys
if len(sys.argv) !=3:
    print 'usage: filecopy source destination'
else:
    try:
        infile = open(sys.argv[1])
        outfile = open(sys.argv[2], 'w')

    except IOError:
        print 'source file does not exist'


    getline(infile, line)
    infile.close()
    outfile.close()

As you can hopefully see I am trying to output why the program won't work if the user tries to use it wrong.

I recently wrote a c++ program doing the same thing as this, and it worked just fine, but now I have to transfer the same logic into a different syntax.

Upvotes: 1

Views: 1697

Answers (3)

Dibyansu
Dibyansu

Reputation: 1

from sys import argv

def main () :

        sourcefile = argv [ 1 ]
        destfile = argv [ 2 ]

        sourceptr = open ( sourcefile , 'r')

        destptr = open ( destfile , 'w')

        destptr . write ( sourceptr . read ()  )

        sourceptr . close ()

        destptr . close ()

main ()

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174748

I am trying to write a line of infile into the string line and then write that into an output file.

Don't try to "write C++" in Python. For the task at hand:

import sys

if len(sys.argv) !=3:
    print('usage: filecopy source destination')
else:
    try:
        with open(sys.argv[1], 'r') as inf, open(sys.argv[2], 'w') as outf:
            for line in inf:
               outf.write(line)
    except IOError:
        print('{} does not exist or cannot be read'.format(sys.argv[1]))

Upvotes: 1

Neel
Neel

Reputation: 21329

Remove unwanted spaces from your code. It might work.

I already edited you post, please try to run this code.

You have to handle try...except if file not exist.

import shutil
import sys
if len(sys.argv) !=3:
    print 'usage: filecopy source destination'
else:
    try:
        shutil.copyfile(sys.argv[1], sys.argv[2])
    except IOError:
        print 'source file does not exist'

Upvotes: 0

Related Questions