类型错误需要字符串或缓冲区,在python中找到文件

时间:2012-07-11 18:15:14

标签: python

因此,当我单独编写这段代码时,它工作正常,但当我将它们组合在一起时,它会给我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))

1 个答案:

答案 0 :(得分: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.