當我運行這段代碼時,出現上述錯誤。我會明白,如果是因爲我的對象之一都沒有被認定爲串,但第一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()
只是說明:''用'mode ='打開'''''將會附加到現有文件中(如果存在的話)不能保證它會「創建」一個文件而不是改變一個現有的文件。如果文件不存在,'mode =「w」'將清空現有文件並讓你編寫新內容或打開一個新文件,而在現代Python 3中,'mode =「x」'將只創建新文件,如果您覆蓋了現有的文件,則會引發異常。 – ShadowRanger