TypeError: coercing to Unicode: need string or buffer

Question:

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..100t([+-])chr(d+):(d+)..(d+).+$',k)
            if not x:
                continue
            out_f.write(' '.join(x[0]) + 'n')
    

Please someone help me.

Asked By: madkitty

||

Answers:

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.

Answered By: Gareth Rees

You’re trying to pass file objects as filenames. Try using

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

at the top of your code.

(Not only does the doubled usage of open() cause that problem with trying to open the file again, it also means that infile and outfile are never closed during the course of execution, though they’ll probably get closed once the program ends.)

Answered By: JAB

For the less specific case (not just the code in the question – since this is one of the first results in Google for this generic error message. This error also occurs when running certain os command with None argument.

For example:

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

Will raise this exception when arg is None.

Answered By: Eran

Here is the best way I found for Python 2:

def inplace_change(file,old,new):
        fin = open(file, "rt")
        data = fin.read()
        data = data.replace(old, new)
        fin.close()

        fin = open(file, "wt")
        fin.write(data)
        fin.close()

An example:

inplace_change('/var/www/html/info.txt','youtub','youtube')
Answered By: George Chalhoub
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.