2013-12-09 26 views
0

這應該把這個信息放到一個新的文件,但我得到一個錯誤,說'tuple' object has no object 'write'所以我需要一些幫助來找出我的代碼中有什麼問題。得到這個文件並擺脫錯誤代碼

def codeData(filename): 
    file = open(filename) 
    outputFile = ("Project.txt", "w") 
    #makes file that will take information from given file and write on it 
    clinic = file.readline().strip() #takes the name of clinic and writes it 
    patientnumber = int(file.readline().strip()) #takes the amount of patients 

    for i in range(patientnumber):  
     outputFile.write("<patient>\n") 
     outputFile.write("<patientID>"+file.readline().strip()+"</patientID>\n") 
     outputFile.write("<clinic>"+clinic+"</clinic>\n") 
     age = int(file.readline().strip()) 
     outputFile.write("<age>"+str(age)+"</age>\n") 

     outputFile.write("<gender>"+gender+"</gender>\n")  
     height = int(file.readline().strip()) 

     outputFile.write("<height>"+str(height)+"</height>\n") 
     weight = int(file.readline().strip()) 

     outputFile.write("<weight>"+str(weight)+"</weight>\n") 
     hba1 = int(file.readline().strip()) 

     outputFile.write("<hba1>"+str(hba1)+"</hba1>\n") 
     cholesterol = int(file.readline().strip()) 

     outputFile.write("<cholesterol>"+str(cholesterol)+"</cholesterol>\n") 

     outputFile.write("<smoker>"+smoker+"</smoker>\n") 

     systolic = int(file.readline().strip()) 
     outputFile.write("<systolic>"+str(systolic)+"</systolic>\n") 

     diastolic = int(file.readline().strip()) 
     outputFile.write("<diastolic>"+str(diastolic)+"</diastolic>\n") 

     file.close() 
     outputFile.close() 

    codeData("Project Text.txt") 

這裏是什麼是對,它在

UHIC 
2 
A31415 
54 
M 
180 
90 
6.7 
100 
No 
130 
65 
A32545 
62 
F 
160 
80 
7.2 
120 
Yes 
180 
92 
+0

好的更新這個問題是,我得到它貫穿一次,它通過列表的第一部分工作,但我需要它再次通過,我不能讓它做到這一點,所以如果有人知道如何解決這個請幫忙? – user3084628

回答

0

花費的tuple沒有一個write方法正在發生的事情,因爲你沒有打開過你的輸出文件錯誤的文件,你只要把那個將被傳遞給open括號中的參數:

outputFile = ("Project.txt", "w") # need to call open here! 

但是,你應該使用with語句來打開和關閉你的兩個文件:

with open(filename) as file, open("Project.txt", "w") as outputFile: 
    # the rest of your code, skipping the close calls 

你有一個單獨的錯誤,其中close電話都是你的循環中。使用with使手動關閉完全不需要,所以你不必擔心在哪裏打電話。

進一步的建議,與您當前的錯誤無關:如果您正在讀取或寫入結構化文件格式(如XML),則應該爲該輸入或輸出使用專用模塊。學習API比使用自己的代碼編寫API容易得多,而且更有可能使其正確工作。例如,當手動編寫XML時,確保您正確關閉所有標籤可能會非常棘手。 (您的代碼沒有出現在任何地方關閉其<patient>標籤,所以這可能適用於你!)

我覺得對於XML而言,ElementTree模塊(xml.etree)可能是去,如果你想在東西的路上標準庫,但我從來沒有真正使用它,所以我不能說話權威。還有xml.dom.minidom加上一些第三方模塊。其他擁有更多經驗的人可能會提供更好的關於這些選擇的建議。