Python 在服务器上找不到文件时阻止代码崩溃的方法?
所以我的问题是,当其中一个在服务器中找不到文件时,我的代码会崩溃。当没有找到文件时,是否有方法跳过查找过程并继续循环。 下面是我的代码:Python 在服务器上找不到文件时阻止代码崩溃的方法?,python,file,loops,crash,Python,File,Loops,Crash,所以我的问题是,当其中一个在服务器中找不到文件时,我的代码会崩溃。当没有找到文件时,是否有方法跳过查找过程并继续循环。 下面是我的代码: fname='/Volumes/database/interpro/data/'+uniprotID+'.txt' for index, (start, end) in enumerate(searchPFAM(fname)): with open('output_'+uniprotID+'-%s.txt' % index,'w') as fi
fname='/Volumes/database/interpro/data/'+uniprotID+'.txt'
for index, (start, end) in enumerate(searchPFAM(fname)):
with open('output_'+uniprotID+'-%s.txt' % index,'w') as fileinput:
print start, end
for item in lookup[uniprotID]:
item, start, end = map(int, (item, start, end)) #make sure that all value is int
if start <= item <= end:
print item
result = str(item - start)
fileinput.write(">{0} | at position {1} \n".format(uniprotID, result))
fileinput.write(''.join(makeList[start-1:end]))
break
else:
fileinput.write(">{0} | N/A\n".format(uniprotID))
fileinput.write(''.join(makeList[start-1:end]))
对于枚举(searchPFAM(fname))中的索引(开始、结束):
以open('output'+uniprotID+'-%s.txt'%index,'w')作为文件输入:
打印开始、结束
对于查找[uniprotID]中的项:
item,start,end=map(int,(item,start,end))#确保所有值都是int
如果启动您需要使用块处理异常。有关详细信息,请参阅Python文档
在这种情况下,您必须用try
包装open()
调用(以及块中的所有内容),并用except IOError
捕获异常:
for ...
try:
with open(...
# do stuff
except IOError:
# what to do if file not found, or pass
附加信息
您真正应该做的是,将外部for
循环的主体拉出到函数中。或者将带有
的的主体插入到处理打开的文件的函数中。无论哪种方式,减少嵌套都会使事情更具可读性,也更容易进行类似这样的更改,添加try
/,除了
实际上,您似乎在每次迭代外部for
循环时都会重新打开该文件,但文件名从未更改-您总是重新打开同一个文件。这是故意的吗?如果没有,您可能想重新思考您的逻辑,并将其转移到循环之外
仔细想想,你得到的例外是什么?这是一个找不到文件的错误吗?因为您正在打开文件进行写入('w'
),所以我不确定您为什么会出现异常。对于枚举(searchPFAM(fname))中的索引(start,end)):
for index, (start, end) in enumerate(searchPFAM(fname)):
try:
newname = 'output_'+uniprotID+'-%s.txt' % index
with open(newname,'w') as fileinput:
print start, end
for item in lookup[uniprotID]:
item, start, end = map(int, (item, start, end)) #make sure that all value is int
if start <= item <= end:
print item
result = str(item - start)
fileinput.write(">{0} | at position {1} \n".format(uniprotID, result))
fileinput.write(''.join(makeList[start-1:end]))
break
else:
fileinput.write(">{0} | N/A\n".format(uniprotID))
fileinput.write(''.join(makeList[start-1:end]))
except IOError:
print 'Couldn't find file %s' % newname
尝试:
newname='output_u'+uniprotID+'-%s.txt'%index
以open(newname,'w')作为文件输入:
打印开始、结束
对于查找[uniprotID]中的项:
item,start,end=map(int,(item,start,end))#确保所有值都是int
如果start我不明白你所说的用块包装open()调用(以及其中的所有内容)是什么意思?那就是操作系统我得到的IOError:找不到文件