这是什么意思:AttributeError:' str'对象没有属性'写'

时间:2016-03-05 03:57:04

标签: python

当我去运行此代码时,我得到上面的错误。我理解是否因为我的某个对象尚未被识别为字符串,但错误出现在第一个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()

2 个答案:

答案 0 :(得分:4)

您应该使用itinerary_file.writeitinerary_file.close,而不是file_name.writefile_name.close

此外,open(file_name, "a")而非open('file_name', "a"),除非您尝试打开名为file_name而非itinerary.txt的文件。

答案 1 :(得分:1)

属性错误意味着您尝试与之交互的对象没有您正在调用的项目。

例如

>>> a = 1

>>> a.append(2)

a不是列表,它没有附加函数,因此尝试这样做会导致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"))