When I go to run this code, I get the error above. I would understand if it was because one of my objects haven't been identified as strings but the error appears on the first file_name.write()
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()
You should be using itinerary_file.write
and itinerary_file.close
, not file_name.write
and file_name.close
.
Also, open(file_name, "a")
and not open('file_name', "a")
, unless you're trying to open a file named file_name
instead of itinerary.txt
.
An attribute error means that the object your trying to interact with, does not have the item inside it you're calling.
For instance
>>> a = 1
>>> a.append(2)
a is not a list, it does not have an append function, so trying to do this will cause an AttributError exception
when opening a file, best practice is usually to use the with
context, which does some behind the scenes magic to make sure your file handle closes. The code is much neater, and makes things a bit easier to read.
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"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.