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 fil开发者_运维技巧e has copied"
For reference, I'm using Python v2.7.1
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.
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!'
copyfile doesn't return a value (well, returns None).
加载中,请稍侯......
精彩评论