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 に答える