本人解释,这个标题纯属噱头,为了赚一点点击率,其实应该叫,《用python的catch捕获无关紧要的异常》。
废话不多说,上实际情况。
def open(self):
strFilter="document file(*.docx);;text file(*.txt)"
fileName,_=QFileDialog.getOpenFileName(self,'选择要打开的文件','c:\\',strFilter,"document file(*.docx)")
if(fileName.endswith("txt"))
file=QFile()
file.setFileName(fileName)
strText=str()
if(file.open(QFile.ReadOnly|QFile.Text)):
input=QTextStream(file)
strText=input.readAll()
print(strText)
self.textEdit.setText(strText)
else:
strText=""
document = Document(fileName)
for paragraph in document.paragraphs:
strText+=paragraph.text
print(strText)
self.textEdit.setText(strText)
这段代码大意是通过python自带的open和python读取word的document模块来达到选择电脑上的word或者txt文件打开并读写到textEdit控件的目的。事实证明它运行的很好。
但是有个问题,如果我不选择文件并关闭对话框,我的代码中因为缺少处理打开文件内容为空的部分,这时候就会报错闪退,虽然它明明对我的程序没什么影响。这时有两种处理方法,1、在代码中增加处理部分,类似if(file.read()==null)的代码,但感觉比较麻烦。2、对不影响程序运行的异常,直接catch不处理就可以了。如下:
def open(self):
strFilter="document file(*.docx);;text file(*.txt)"
fileName,_=QFileDialog.getOpenFileName(self,'选择要打开的文件','c:\\',strFilter,"document file(*.docx)")
if(fileName.endswith("txt")):
try:
file=QFile()
file.setFileName(fileName)
strText=str()
if(file.open(QFile.ReadOnly|QFile.Text)):
input=QTextStream(file)
strText=input.readAll()
print(strText)
self.textEdit.setText(strText)
except Exception:
None
else:
try:
strText=""
document = Document(fileName)
for paragraph in document.paragraphs:
strText+=paragraph.text
print(strText)
self.textEdit.setText(strText)
except Exception:
None
这样就算不打开文件关闭对话框也就ok了。