Python文件错误

Python文件错误,python,Python,我正在练习用Python编写文件,但是发生了一些不好的事情 这里仍然有一些错误: File = input("Please enter the name for your txt. file: ") fileName = (File + ".txt") WRITE = "w" APPEND = "a" file = [] name = " " while name != "DONE" : name = input("Please enter the guest name (Ent

我正在练习用Python编写文件,但是发生了一些不好的事情

这里仍然有一些错误:

File = input("Please enter the name for your txt. file: ")

fileName = (File + ".txt")
WRITE = "w"
APPEND = "a"

file = []
name = " "
while name != "DONE" :
    name = input("Please enter the guest name (Enter DONE if there is no   more names) : ").upper()
   fileName.append(name)
fileName.remove("DONE")
print("The guests list in alphabetical order, and it will save in " + fileName + " :")
file.sort()
for U in file :
    print(U)
file = open(fileName, mode = WRITE)
file.write(name)
file.close()
print("file written successfully.")

仍然显示“str”错误。

Python字符串是不可变的。因此,不能对它们使用
append()
。改用
+=

fileName.remove("DONE")
这是

fileName += name
请注意,如何不向字符串追加任何内容,而是创建一个新的字符串,然后将其分配给
文件名

。 我以为你弄错了变量名

fileName = fileName + name

使用上面的代码

就在bat之外,您不能附加到toople

filename=filename+name
另一件事,我不知道您使用的是什么版本的python,但我从未见过这样的表达式

fileName.append(name) #how can you append or remove anything into or from this when it contains toople?

只需全面检查您的代码。就像我说的,你不能从一个图普中添加或删除东西;仅在列表和字典中。

append
是代码中声明的文件名被视为字符串的位置。如果要将字符串附加到文件,请以“附加”模式打开文件并写入:

file = open(fileName, mode = WRITE) #this should be something like (file=open(fileName,"w"))
file = open(fileName, mode = WRITE) #this should be something like (file=open(fileName,"w"))
with open(aFile + ".txt", "a") as f:
    f.write("appended text")