2012-04-24 89 views
3

我試圖編寫一個代碼來讀取文件並對其進行一些操作。TypeError:強制轉換爲Unicode:需要字符串或緩衝區,找到類型

代碼:

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

錯誤我得到:

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 

我怎麼運行程序:

python assembler.py Add.asm 

其中Add.asm ID我想讀取文件,所有模塊都在同一個庫中,包括.asm文件。

+3

'file'是python中的一個內置類型,不要將這個名稱用於你的變量。 – georg 2012-04-24 19:40:22

回答

6

您有多個問題。

首先,您的縮進不一致。這意味着進口被認爲是assem函數的一部分,但沒有別的。從字面上講,你必須知道的第一件事是縮進是重要的。其次,您正在使用內置函數名稱file作爲變量的名稱。不要這樣做。

第三,你實際上沒有調用assem函數。但由於你的第一個問題,第一個沒有縮進的行在啓動時執行。因此,當達到input = open(file, 'r')行時,file仍然指內置函數,而不是您的變量(此處未定義)。

最後,雖然這實際上並不會導致您的問題,但您不需要同時執行import myParserfrom myParser import Parser。選一個。

+0

請隔離,集中並回答有關問題,即「TypeError」。其他其他問題(例如縮進)是無關緊要的。人們希望找到關於特定問題的答案,而不是紙質考試! – Apostolos 2018-01-26 09:57:20

-1

File "C:\Python27\lib\ntpath.py", line 488, in abspath path = _getfullpathname(path) TypeError: coercing to Unicode: need string or buffer, builtin_function_or_method found

相關問題