TypeError: forced to Unicode: need a string or buffer

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: forced to Unicode: need a line or buffer, found file

    # 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 help me.

+47
python string typeerror
Jul 13 '11 at 13:55
source share
3 answers

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

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

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

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

open , of course, expects its first argument to be the file name, not the open file!

Open the file only once, and everything will be fine.

+51
Jul 13 2018-11-11T00:
source share

You are trying to pass file objects to file names. Try using

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

at the top of the code.

(Not only double the use of open() causes this problem when trying to open the file again, it also means that infile and outfile never close at runtime, although they will probably close after program termination.)

+8
Jul 13 2018-11-11T00:
source share

For a less specific case (and not just the code in the question - since this is one of the first results on Google for this general error message. This error also occurs when you run a specific os command with the None argument.

For example:

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

Raises this exception if arg is None.

+5
Oct 21 '15 at 5:34
source share



All Articles