Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 这意味着什么:AttributeError:';str';对象没有属性';写';_Python - Fatal编程技术网

Python 这意味着什么:AttributeError:';str';对象没有属性';写';

Python 这意味着什么:AttributeError:';str';对象没有属性';写';,python,Python,当我运行这段代码时,我得到了上面的错误。如果是因为我的一个对象没有被识别为字符串,但错误出现在第一个文件\u name.write() 您应该使用行程文件。写入和行程文件。关闭,而不是文件名。写入和文件名。关闭 另外,open(file\u name,“a”)和notopen(“file\u name”,“a”),除非您试图打开一个名为file\u name的文件,而不是itineray.txt,属性错误意味着您试图与之交互的对象中没有您正在调用的项目 比如说 >a=1 >a.append(2)

当我运行这段代码时,我得到了上面的错误。如果是因为我的一个对象没有被识别为字符串,但错误出现在第一个
文件\u name.write()


您应该使用
行程文件。写入
行程文件。关闭
,而不是
文件名。写入
文件名。关闭


另外,
open(file\u name,“a”)
和not
open(“file\u name”,“a”)
,除非您试图打开一个名为
file\u name
的文件,而不是
itineray.txt
,属性错误意味着您试图与之交互的对象中没有您正在调用的项目

比如说

>a=1

>a.append(2)

a不是列表,它没有附加函数,因此尝试这样做将导致AttributeError异常

打开文件时,最佳做法通常是将
上下文一起使用,这会产生一些幕后魔法,确保文件句柄关闭。代码更加整洁,并且使内容更易于阅读

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"))

稍微澄清一下错误:它的意思是“您试图对字符串的某个对象调用函数write()!”。文件名是一个字符串,因此会出现错误。坦率地说,您不需要调用
行程\u file.close()
,因为您应该使用确保和可预测的关闭行为,同时消除意外忘记或仅有条件地执行
close()
的风险。是的,这是正确的答案。我感谢你们两位的建议,拯救了一个年轻人的生命。@ShadowRanger 100%同意将
一起使用!请注意:
open
ing with
mode=“a”
将附加到现有文件(如果存在);不能保证它将“创建”一个文件,而不是改变一个现有的文件
mode=“w”
将清空现有文件,如果文件不存在,则允许您编写新内容或打开新文件;在现代Python 3中,
mode=“x”
将仅创建新文件,如果您将覆盖现有文件,则会引发异常。
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"))