我正在使用file.index
在文件中搜索字符串。更改file.index的默認值ValueError
def IfStringExistsInFile(self,path,lineTextCheck):
file = open(path).read()
if file.index(lineTextCheck):
print (lineTextCheck + " was found in: " + path)
else:
raise ValueError (lineTextCheck + " was NOT found in: " + path)
我的問題是,如果沒有找到該字符串,它會自動提高默認ValueError異常,並不會進入其中包含我的自定義ValueError異常的「其他」代碼:
ValueError: substring not found
有我可以改變這個默認的ValueError的方法?
目前,我想出的唯一辦法是換句用「嘗試除」,就像這樣:
def IfStringExistsInFile(self,path,lineTextCheck):
file = open(path).read()
try:
if file.index(lineTextCheck):
print (lineTextCheck + " was found in: " + path)
except:
raise ValueError(lineTextCheck + " was NOT found in: " + path)
沒有更好的辦法,將不勝感激。先謝謝你!
完美,謝謝:) –