2011-07-13 56 views
47

此代码返回以下错误消息:类型错误:强迫为Unicode:需要字符串或缓冲区

  • 张开(infile中,模式= 'R',缓冲= -1)作为IN_F,开放(OUTFILE ,模式= 'W',缓冲= -1)为out_f: 类型错误:强迫为Unicode:需要字符串或缓冲区,文件中发现

    # Opens each file to read/modify 
    infile=open('110331_HS1A_1_rtTA.result','r') 
    outfile=open('2.txt','w') 
    
    import re 
    
    with open (infile, mode='r', buffering=-1) as in_f, open (outfile, mode='w', buffering=-1) as out_f: 
        f = (i for i in in_f if i.rstrip()) 
        for line in f: 
         _, k = line.split('\t',1) 
         x = re.findall(r'^1..100\t([+-])chr(\d+):(\d+)\.\.(\d+).+$',k) 
         if not x: 
          continue 
         out_f.write(' '.join(x[0]) + '\n') 
    

请帮助我的人。

回答

53

您试图打开每个文件两次!首先,你做的事:

infile=open('110331_HS1A_1_rtTA.result','r') 

,然后你再通过infile(这是一个文件对象),将open功能:

with open (infile, mode='r', buffering=-1) 

open当然希望它的第一个参数是一个文件名,不是打开的文件!

只打开一次文件,你应该没问题。

+0

这么吓人真棒。谢谢! – 2013-11-07 16:13:04

8

您试图将文件对象作为文件名传递。尝试使用

infile = '110331_HS1A_1_rtTA.result' 
outfile = '2.txt' 

位于代码顶部。

(不仅的open()双倍使用事业试图再次打开该文件的问题,这也意味着infileoutfile执行过程中是从来不关,虽然他们可能会得到关闭一次程序)

5

对于不太具体的情况(不仅仅是问题中的代码 - 因为这是Google针对此类一般性错误消息的首个结果之一,在使用无参数运行某些os命令时也会发生此错误。

例如:

os.path.exists(arg) 
os.stat(arg) 

当arg为无时会引发此异常。

+0

谢谢你。该python错误代码是真的误导。 – mjuarez

相关问题