0

I have a function that adds a date to the contents of the file 'completed.txt' every time I call on it and supply the date. The function is as below :

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"

where libspath is the path to the text file. Now when I call on it say completed('2000.02.16'), it writes the date into the completed.txt file. When I try adding another date to it say completed('2000.03.18') then it overwrites the previous date and only '2000.03.18' is now in the text file but I want both the dates to be available in the file to use it as a record

lets_try
  • 15
  • 1
  • 6
  • possible duplicate of [How do you append to a file in Python?](http://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file-in-python) – Mel Jun 30 '15 at 07:41

2 Answers2

0

You have to open the file in append mode:

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."

From Python docs

with open('completed.txt', 'a') as fileobject:
    fileobject.write(date + ' \n')
ssundarraj
  • 809
  • 7
  • 16
0
fileobject=open('completed.txt',"a") 

                                 ^^

Open in append mode. You should use

with open("completed.txt", "a") as myfile:
    myfile.write(date+' \n')
vks
  • 67,027
  • 10
  • 91
  • 124