这意味着什么:attributeRor:“str”对象没有“write”属性

2024-04-20 04:25:29 发布

您现在位置: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()

Tags: of对象字符串代码name错误destinationlength
2条回答

属性错误意味着试图与之交互的对象中没有要调用的项。

例如

>>> a = 1

>>> a.append(2)

a不是列表,它没有append函数,因此尝试执行此操作将导致attributeerror异常

打开文件时,最佳实践通常是使用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"))

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

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

相关问题 更多 >