2016-03-05 35 views
1

當我運行這段代碼時,出現上述錯誤。我會明白,如果是因爲我的對象之一都沒有被認定爲串,但第一file_name.write()這是什麼意思:AttributeError:'str'對象沒有屬性'寫'

def save_itinerary(destination, length_of_stay, cost): 
    # Itinerary File Name 
    file_name = "itinerary.txt" 

    # Create a new file 
    itinerary_file = open('file_name', "a") 

    # Write trip information 
    file_name.write("Trip Itinerary") 
    file_name.write("--------------") 
    file_name.write("Destination: " + destination) 
    file_name.write("Length of stay: " + length_of_stay) 
    file_name.write("Cost: $" + format(cost, ",.2f")) 

    # Close the file 
    file_name.close() 
+0

只是說明:''用'mode ='打開'''''將會附加到現有文件中(如果存在的話)不能保證它會「創建」一個文件而不是改變一個現有的文件。如果文件不存在,'mode =「w」'將清空現有文件並讓你編寫新內容或打開一個新文件,而在現代Python 3中,'mode =「x」'將只創建新文件,如果您覆蓋了現有的文件,則會引發異常。 – ShadowRanger

回答

4

出現錯誤,您應該使用itinerary_file.writeitinerary_file.close,不file_name.writefile_name.close

另外,open(file_name, "a")而不是open('file_name', "a"),除非您嘗試打開名爲file_name而不是itinerary.txt的文件。

+2

爲了澄清這個錯誤:它意味着「你試圖在某個字符串的東西上調用函數write()!」。 file_name是一個字符串,因此是錯誤。 –

+1

坦率地說,你不需要調用'itinerary_file.close()'因爲你應該使用['with'語句](https://docs.python.org/3/reference/compound_stmts.html#with)獲得有保證且可預測的關閉行爲,同時消除意外遺忘或僅有條件地執行'close()'的風險。但是,是的,這是正確的答案。 – ShadowRanger

+0

我很欣賞你們倆的建議,挽救了一個年輕人的生命。 –

1

屬性錯誤意味着您嘗試與之交互的對象沒有您要調用的項目。

例如

>>> a = 1

>>> a.append(2)

一個不是列表,它不具有附加功能,所以試圖在打開時不這樣做將導致AttributError例外

一個文件,最好的做法通常是使用with上下文,它會在幕後做一些魔術來確保你的文件句柄關閉。代碼更加整潔,讓事情更容易閱讀。

def save_itinerary(destination, length_of_stay, cost): 
    # Itinerary File Name 
    file_name = "itinerary.txt" 
    # Create a new file 
    with open('file_name', "a") as fout: 
     # Write trip information 
     fout.write("Trip Itinerary") 
     fout.write("--------------") 
     fout.write("Destination: " + destination) 
     fout.write("Length of stay: " + length_of_stay) 
     fout.write("Cost: $" + format(cost, ",.2f"))