You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 (like my_list.append(item)), not for file objects created by open().
  • When you use open() to access a file, it returns a _io.TextIOWrapper object — this type uses write() to add content, not append().

修正后的完整代码

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 to open() 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 .txt so 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:43:47