python - 正确值的文件输出错误

标签 python file list

我的目标是将 makeList 的索引打印到另一个文件上。我检查了开始值和结束值,结果是正确的。然而,我的输出文件完全关闭,因为它只在该文件上打印一个字符。

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) 

最佳答案

移动线:

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) 

预计到达时间:使用列表切片有一种更简单的方法:

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)

关于python - 正确值的文件输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11423994/

相关文章:

python - 安装并运行 tensorflow

python:检查jpg的url是否存在

python - 如何在 pyjade 中包含内联内容

Java输入流追加而不删除

list - Prolog二进制列表问题

python - 未实现错误: X is not picklable

c++ - 无法关闭 OPENFILENAME

java - 尝试在 Java 中构建

python - 为什么 python 中的列表操作在函数范围之外运行?

python - Python 中的字符串列表乘法