2012-07-11 44 views
0

因此,当我分别写这段代码时,它工作正常,但是当我将它们组合在一起时,它会给我typeError。为什么会发生?我不明白,当我分别写他们,它工作正常。在此先感谢:)类型错误需要字符串或缓冲区,在Python中找到的文件

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)) 

回答

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. 
+0

seek()里面的数字是什么意思,你是说我应该使用open(outputFile,'r +)作为dile和outputFile.seek(0)和outputFile.read() – 2012-07-11 18:26:53

+0

查找内部的数字('0')是文件位置。在这种情况下,0是文件的开始。是的,我的意思是使用open(outputFile,'r +)',而不是去寻找,看看我更新的答案,它将所有文本放在一起,然后一次性写入,保留对' textwrap' – mgilson 2012-07-11 18:28:40

+0

我想我的目标是编写文件并对其进行格式化,以便每行只有6个字符 – 2012-07-11 18:29:22

相关问题