Reputation: 519
I'm trying to get Python to print a sentence if it successfully copies a file. While it copies the file, it ignores the print. why is this? here's a similar example of my code:
from shutil import copyfile
if copyfile('/Library/demo.xls','/Jobs/newdemo.xls'):
print "the file has copied"
For reference, I'm using Python v2.7.1
Upvotes: 0
Views: 1051
Reputation: 7780
copyfile
does not return anything, but it throws an exception if an error occurs. Use the following idiom instead of the if
check:
import shutil
try:
shutil.copyfile('/Library/demo.xls','/Jobs/newdemo.xls')
except (Error, IOError):
# Handle error
pass
else:
# Handle success
print "the file has copied"
Link to the shutil.copyfile
documentation.
Upvotes: 9
Reputation: 53819
That's because shutil.copyfile
returns None
. You probably want to wrap it in a try
/except
clause instead:
try:
shutil.copyfile(file1, file2)
print 'success!'
except shutil.Error:
print 'oh no!'
Upvotes: 4