2016-03-05 32 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"))