我的目标是将makeList的索引打印到另一个文件中。我已经检查了我的起始值和结束值,结果是正确的。但是,我的outputFile是完全关闭的,因为它只在该文件上打印一个字符。你知道吗
def printOutput(start, end, makeList):
if start == end == None:
return
else:
while start <= end:
print start
print end
outputFile = open('out'+uniprotID+'.txt','w')#file for result output
inRange = makeList[start]
start += 1
outputFile.write(inRange)
移动线条:
到while循环之前的行。现在,它正在while循环的每个迭代中重新打开该文件(作为一个全新的空文件)。你知道吗
所以代码是:
ETA:使用列表切片有一种更简单的方法:
如前所述,问题是输出文件在循环中被重复打开。解决方法是在进入循环之前打开输出文件。你知道吗
这里还有一个版本,使用
with
打开文件。使用此结构的优点是,当您完成操作或遇到异常时,它将自动为您关闭文件。你知道吗否则,您必须记住显式地用
outputFile.close()
关闭文件。你知道吗发生这种情况是因为您多次打开文件进行写入。基本上,这使得程序在
while
循环的每次迭代中都覆盖文件。你知道吗要最小限度地修改代码,请使用
'a'
标志而不是'w'
标志打开文件。这将以append
模式而不是overwrite
模式打开文件。你知道吗但是,这将使您的代码重复打开文件,这将导致文件速度减慢,因为磁盘I/O操作需要时间。相反,更好的方法是在
while
循环外部打开文件进行写入,然后在内部写入。在代码中:相关问题 更多 >
编程相关推荐