1

我正在 Python 上制作“日记”或“日记”程序。它非常简单,你写下日期,然后写日记,你可以随时阅读它,你可以继续添加笔记或新条目。现在,我想存储用户的输入,以便当他第二天进入时,他可以阅读他写的内容并为他/她的日记写一个新条目,但我找不到这样做的方法。我在 StackOverflow 上找不到这个问题,抱歉,如果它已经被问过了。

4

1 回答 1

0

写入文本文件:

    # \n is a newline.
    date = "23/3/2014 \n"
    entry = "this is my diary entry \n"
    f = open("diary.txt", "a") # a means append, this stops new data overwriting old
    f.write(date)
    f.write(entry)
    f.close()

从文本文件中读取:

    g = open("diary.txt", "r") # r means read-only, you cannot write to file that is opened like this
    entries = g.readlines()
    g.close()
    for each in entries:
        print 

如果您甚至需要这样做,您将遇到的唯一困难是在读取文件时解析文件,但这超出了问题的范围。

于 2014-03-23T22:09:20.330 回答