python - 如何在 Python 中添加到文件末尾?

标签 python python-3.x

我有一个关于家庭作业记事本的好主意,并且我编写了该程序的基础知识。问题是,当我添加更多内容(重新运行程序)时,所有内容都会被清除并替换为新的作业。有什么办法可以解决这个问题吗?

def query_period(agenda_file):
    per = input("What period is it?")

    if per in ["1", "2", "3", "4", "5", "6", "7", "8"]:
        input_and_write_homework(agenda_file)
    else:
        print("Invalid choice")

def input_and_write_homework(file):
    hw = raw_input("What is the homework?")
    file.write(hw)

if __name__ == "__main__":
    agenda = open("agenda.txt", "w+")
    query_period(agenda)
    agenda.close()

最佳答案

要在 python 中附加到文件,请使用“a”属性,因此请更改:

agenda=open("agenda.txt","w+")

至:

agenda=open("agenda.txt","a")

您可能应该使用 raw_input() 并将类型转换为字符串,而不是 input()。

关于python - 如何在 Python 中添加到文件末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8860288/

相关文章:

python - 有没有办法从网站的检查菜单中获取有关元素的信息?

python - Pyomo: KeyError: "Index ' (0, 1, 1 )' is not valid for indexed component ' x_ijl'"

python - 使用scipy差分进化对参数的约束

python - 如何为我的博客中的帖子实现 'Vote up' 系统?

Python 3 索引超出范围错误

multithreading - 使用 Python 和多线程处理巨大的 CSV 文件

python - Seaborn 直方图使列变白

python - 缺少 sphinx 命令的 conf 文件

python - 如何在 matplotlib 中创建引脚图

python - 不能设置双轴位置