[英]What does this mean: AttributeError: 'str' object has no attribute 'write'
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()
我会理解是否是因为我的一个对象没有被识别为字符串,但是错误出现在第一个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
. 您应该使用itinerary_file.write
和itinerary_file.close
,而不是file_name.write
和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
. 此外, open(file_name, "a")
和不open('file_name', "a")
除非你试图打开一个文件名为file_name
代替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 a不是列表,它没有附加函数,因此尝试执行此操作将导致AttributError异常
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. 在打开文件时,最佳实践通常是使用with
上下文,它会在后台进行魔术操作以确保关闭文件句柄。 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"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.