正确值的文件输出错误

2024-09-28 03:14:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是将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) 

Tags: 文件none目标returnifdef字符start
3条回答

移动线条:

outputFile = open('out'+uniprotID+'.txt','w')#file for result output

到while循环之前的行。现在,它正在while循环的每个迭代中重新打开该文件(作为一个全新的空文件)。你知道吗

所以代码是:

def printOutput(start, end, makeList):
  if start == end == None:
      return
  else:
      outputFile = open('out'+uniprotID+'.txt','w')#file for result output
      while start <= end:
          print start
          print end
          inRange = makeList[start]
          start += 1
          outputFile.write(inRange) 

ETA:使用列表切片有一种更简单的方法:

def printOutput(start, end, makeList):
  if start == end == None:
      return
  else:
      outputFile = open('out'+uniprotID+'.txt','w')#file for result output
      for inRange in makeList[start:end+1]:
          outputFile.write(inRange)

如前所述,问题是输出文件在循环中被重复打开。解决方法是在进入循环之前打开输出文件。你知道吗

这里还有一个版本,使用with打开文件。使用此结构的优点是,当您完成操作或遇到异常时,它将自动为您关闭文件。你知道吗

   def printOutput(start, end, makeList):
      if start == end == None:
          return
      else:
          out_fname = 'out'+uniprotID+'.txt'
          with open(out_fname, 'w') as outputFile:
              while start <= end:
                  print start
                  print end
                  inRange = makeList[start]
                  start += 1
                  outputFile.write(inRange) 

否则,您必须记住显式地用outputFile.close()关闭文件。你知道吗

发生这种情况是因为您多次打开文件进行写入。基本上,这使得程序在while循环的每次迭代中都覆盖文件。你知道吗

要最小限度地修改代码,请使用'a'标志而不是'w'标志打开文件。这将以append模式而不是overwrite模式打开文件。你知道吗

但是,这将使您的代码重复打开文件,这将导致文件速度减慢,因为磁盘I/O操作需要时间。相反,更好的方法是在while循环外部打开文件进行写入,然后在内部写入。在代码中:

def printOutput(start, end, makeList):
    if start == end == None:
        return
    else:
        outputFile = open('out'+uniprotID+'.txt','w')#file for result output
        while start <= end:
            print start
            print end
            inRange = makeList[start]
            start += 1
            outputFile.write(inRange)
        outputFile.close()

相关问题 更多 >

    热门问题