Itzik984 Itzik984 - 1 month ago 32
Python Question

TypeError: coercing to Unicode: need string or buffer, type found

I'm trying to write a code that will read a file and make some manipulations on it.

the code:

def assem(file):
import myParser
from myParser import Parser
import code
import symboleTable
from symboleTable import SymboleTable

newFile = "Prog.hack"
output = open(newFile, 'w')
input = open(file, 'r')

while prsr.hasMoreCommands():
str = "BLANK"
if(parser.commandType() == Parser.C_COMMAND):


the error i get:

Traceback (most recent call last):
File "", line 11, in <module>
input = open(file, 'r')
TypeError: coercing to Unicode: need string or buffer, type found

how i run the program:

python Add.asm

where Add.asm id the file i want to read, all modules are in the same library, including the .asm file.


You have multiple problems.

Firstly, your indentation is inconsistent. That means that the imports are considered as part of the assem function, but nothing else is. Literally the first thing that you have to know about Python is that indentation is significant.

Secondly, you're using a built-in function name, file, for the name of your variable. Don't do that.

Thirdly, you don't actually call the assem function. But because of your first problem, the first unindented lines are executed on startup. So when the line input = open(file, 'r') is reached, file still refers to the built-in function, not your variable (which isn't defined at this point).

Finally, although this isn't actually causing your problem, you don't need to do both import myParser and from myParser import Parser. Pick one.