TypeError: coercing to Unicode: need string or buffer

PythonStringTypeerror

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Solution 3 - Python

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

Solution 4 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmadkittyView Question on Stackoverflow
Solution 1 - PythonGareth ReesView Answer on Stackoverflow
Solution 2 - PythonEranView Answer on Stackoverflow
Solution 3 - PythonJABView Answer on Stackoverflow
Solution 4 - PythonGeorge ChalhoubView Answer on Stackoverflow