Python-如果操作为true,则打印文本
我试图让Python打印一个句子,如果它成功地复制了一个文件。当它复制文件时,会忽略打印。为什么会这样?下面是我的代码的一个类似示例:Python-如果操作为true,则打印文本,python,printing,if-statement,Python,Printing,If Statement,我试图让Python打印一个句子,如果它成功地复制了一个文件。当它复制文件时,会忽略打印。为什么会这样?下面是我的代码的一个类似示例: from shutil import copyfile if copyfile('/Library/demo.xls','/Jobs/newdemo.xls'): print "the file has copied" 作为参考,我使用的是Python v2.7.1,这是因为shutil.copyfile不返回任何值。您可能希望将其包装在try/exce
from shutil import copyfile
if copyfile('/Library/demo.xls','/Jobs/newdemo.xls'):
print "the file has copied"
作为参考,我使用的是Python v2.7.1,这是因为shutil.copyfile不返回任何值。您可能希望将其包装在try/except子句中:
try:
shutil.copyfile(file1, file2)
print 'success!'
except shutil.Error:
print 'oh no!'
copyfile不会返回任何内容,但如果发生错误,它会引发异常。使用以下习惯用法代替if检查:
指向.复制文件的链接没有返回值,但没有返回任何值。因为在复制完成之前它不知道是否成功?例如,如果文件系统填满了中间副本。
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"