TypeError: coercing to Unicode: need string or buffer

madkitty picture madkitty · Jul 13, 2011 · Viewed 155.8k times · Source

This code returns the following error message:

  • with open (infile, mode='r', buffering=-1) as in_f, open (outfile, mode='w', buffering=-1) as out_f: TypeError: coercing to Unicode: need string or buffer, file found

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

Please someone help me.

Answer

Gareth Rees picture Gareth Rees · Jul 13, 2011

You're trying to open each file twice! First you do:

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

and then you pass infile (which is a file object) to the open function again:

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

open is of course expecting its first argument to be a file name, not an opened file!

Open the file once only and you should be fine.