Python如何通过用户输入追加文件?解决AttributeError报错问题
解决Python文件追加时的AttributeError问题
Hey there! Let's break down why you're hitting that AttributeError and get your file append program working smoothly.
错误原因分析
The error AttributeError: '_io.TextIOWrapper' object has no attribute 'append' makes total sense once you clarify Python object differences:
- The
append()method is for list objects (likemy_list.append(item)), not for file objects created byopen(). - When you use
open()to access a file, it returns a_io.TextIOWrapperobject — this type useswrite()to add content, notappend().
修正后的完整代码
Here's a working version of your program that takes user input and appends it to a file, with key details explained:
# Get input from the user user_content = input("Enter the content you want to append: ") # Open the file in append mode ("a") — creates the file if it doesn't exist # Adding encoding="utf-8" prevents garbled text for non-ASCII characters (like Chinese) with open("my_file.txt", "a", encoding="utf-8") as file_handle: # Use write() instead of append() — add "\n" to put each entry on a new line file_handle.write(user_content + "\n") print("Content successfully appended to the file!")
关键修正与注意事项
- Append Mode: Using
"a"as the second argument toopen()tells Python to add new content to the end of the file (instead of overwriting it). If the file doesn't exist, Python will create it automatically. - Write Instead of Append: File objects rely on
write()to add content. Remember to include"\n"if you want each user input to sit on a separate line (otherwise all entries will be squashed together). - File Naming: In your original code, you had
my_file = "my_file"— it's better to add a file extension like.txtso your system recognizes it as a text file. You can still use a variable for the filename too:file_name = "my_file.txt" with open(file_name, "a", encoding="utf-8") as file_handle: file_handle.write(user_content + "\n")
内容的提问来源于stack exchange,提问作者Jim Jimson
相关产品推荐
相关产品推荐

