0

因此,当我单独编写这段代码时,它可以正常工作,但是当我将它们组合在一起时,它会给我 typeError。为什么会这样?当我单独编写它们时我不明白它工作正常。提前致谢 :)

def printOutput(start, end, makeList):

  if start == end == None:

      return

  else:

      print start, end

      with open('OUT'+ID+'.txt','w') as outputFile:#file for result output
          for inRange in makeList[(start-1):(end-1)]:
              outputFile.write(inRange)
          with open(outputFile) as file:
              text = outputFile.read()
      with open('F'+ID+'.txt', 'w') as file:
        file.write(textwrap.fill(text, width=6))
4

1 回答 1

5

您的问题出在这一行:

 with open(outputFile) as file:

outputFile是一个文件对象(已经打开)。该open函数需要一个字符串(或类似的东西),它是要打开的文件的名称。

如果你想取回文本,你可以一次outputFile.seek(0)又一次outputFile.read()。(当然,您必须以r+模式打开才能使其正常工作。)

也许更好的方法是:

with open('OUT'+ID+'.txt','w') as outputFile:#file for result output
    text=''.join(makeList[(start-1):(end-1)])
    outputFile.write(text)
with open('F'+ID+'.txt', 'w') as ff:
    ff.write(textwrap.fill(text, width=6)) #Version of above file with text wrapped to 6 chars.

编辑

这应该有效:

def printOutput(start, end, makeList):
    if start == end == None:
        return
    else:
        print start, end

        with open('OUT'+ID+'.txt','w') as outputFile:#file for result output
            text=''.join(makeList[(start-1):(end-1)])
            outputFile.write(text)
        with open('F'+ID+'.txt', 'w') as ff:
            ff.write(textwrap.fill(text, width=6)) #Version of above file with text wrapped to 6 chars.
于 2012-07-11T18:19:35.240 回答