Reputation: 65
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
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
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
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