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

20,792

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.

Share:
20,792
Itzik984
Author by

Itzik984

Updated on July 29, 2022

Comments

  • Itzik984
    Itzik984 almost 2 years

    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')
    
    
    prsr=Parser(input)
    while prsr.hasMoreCommands():
          str = "BLANK"
          if(parser.commandType() == Parser.C_COMMAND):
          str="111"+code.comp(prsr.comp())+code.dest(prsr.dest())+code.jump(prsr.jump())+"\n"
    
    output.write(str)
    prsr.advance()
    

    the error i get:

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

    how i run the program:

       python assembler.py Add.asm
    

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