文件内容被覆盖

file contents being overwritten

我有一个函数可以在每次调用它并提供日期时向文件内容添加一个日期 'completed.txt'。函数如下:

def completed(date):
    try:
        os.chdir(libspath)      
        os.system("touch completed.txt")
        fileobject=open('completed.txt',"r+")   
        fileobject.write(date+' \n')
        fileobject.close()

    except:
        print "record.completed(): Could not write contents to completed.txt"

其中 libspath 是文本文件的路径。现在,当我调用它说 completed('2000.02.16') 时,它会将日期写入 completed.txt 文件。当我尝试向它添加另一个日期时说 completed('2000.03.18') 然后它会覆盖以前的日期并且文本文件中现在只有 '2000.03.18' 但我希望这两个日期都在文件中可用以将其用作记录

您必须以附加模式打开文件:

fileobject = open('completed.txt', 'a')

Python Docs for opening file

"It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks."

来自Python docs

with open('completed.txt', 'a') as fileobject:
    fileobject.write(date + ' \n')
fileobject=open('completed.txt',"a") 

                                 ^^

append模式打开。你应该使用

with open("completed.txt", "a") as myfile:
    myfile.write(date+' \n')