Python 3.x 在Python3中从列表中追加

Python 3.x 在Python3中从列表中追加,python-3.x,Python 3.x,我需要将其附加到外部文件,如下所示: def add(): aList = input("Enter file name with file extension too: ") file = open(aList, "a") txt = input("Enter the text you would like to add on to the txt file: ") aList.append (txt); print ("Updated List : "

我需要将其附加到外部文件,如下所示:

def add():
    aList = input("Enter file name with file extension too: ")
    file = open(aList, "a")
    txt = input("Enter the text you would like to add on to the txt file: ")
    aList.append (txt);
    print ("Updated List : ", aList)
此列表称为“list.txt” 我把它作为第一个变量输入,第二个变量输入“Hello”,但我不确定为什么它会给我一个错误。
我只需要将它添加到此列表中…

如果以附加模式打开文件,只需使用write在文件末尾添加文本即可。额外的“\n”插入换行符,以便新输入位于额外的行上

NIGHT
SMOKE
GHOST
TOOTH
ABOUT
CAMEL
BROWN
FUNNY
CHAIR
PRICE
另外,请确保在使用结束时关闭该文件。或者更好地使用with语句,它将在块的and处关闭文件

aList = input("Enter the file name with the file extension too: ")
file = open(aList, "a")
txt = input("Enter the text you would like to add on to the txt file: ")
file.write(txt + '\n');
file.close()
print ("Updated List : ", aList)

你好@ruben fontes,你能告诉我们错误吗?小心缩进->啊,好的,谢谢你的建议。我确实知道这个文件。close()部分,我只是忘了添加它。@RubenFontes我很高兴能帮助你。我自己有时忘记关闭文件。因此,我更喜欢以下语句:)
aList = input("Enter the file name with the file extension too: ")
with open(aList, "a") as file:
    txt = input("Enter the text you would like to add on to the txt file: ")
    file.write(txt + '\n')
print("Updated List : ", aList)