当前位置: 动力学知识库 > 问答 > 编程问答 >

The file in python (AttributeError: 'str' object has no attribute 'append')

问题描述:

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

`

I am just practicing to write the file in Python, but something bad happened. Please help me. Thank you.

The code.

The error description.

Here are still some errors about this :

fileName.remove("DONE")

Still showing 'str' error.

THANK YOU

网友答案:

You try to append to string which is not correct in Python, instead try:

filename += 'name'
网友答案:

You're trying to build a list of names. Start with a list:

guests = []

and then append the values provided by your user:

while name is not "Done":
    prompt = "Please input the name of the next guest, or 'Done'."
    guests.append(input(prompt).upper())

then you can sort that list and write the values to the file. (which you seem to have a handle on)

Appending the guests' names to fileName, or concatenating them onto it, wouldn't make a lot of sense. You'd end up with something like "data.txtJOEBOBJANELINDA" which would do you no good at all.

分享给朋友:
您可能感兴趣的文章:
随机阅读: