0

I am trying to create a file in w+ mode, write some data into it, print that date, close the file, re open it, and write some more data that appends its self to the data already written without losing the original data. I know that the second time i open it not to open it into w+ but w mode figured that out, but I am still stuck.

I am trying to use the .seek(0,2) method to move the pointer to the end of the file and then write. This was a method suggested on here, it seems most people agree it works. It works for me but not when trying to close and reopen files.

# open a new file days.txt in write plus read mode 'w+' 

days_file = open('days.txt', "w+")

# write data to file

days_file.write(" Monday\n Tuesday\n Wednesday\n Thursday\n Friday\n")

# use .seek() to move the pointer to the start read data into days

days_file.seek(0)

days = days_file.read()

# print the entire file contents and close the file

print(days)

days_file.close()

# re open file and use .seek() to move the pointer to the end of the file and add days

days_file = open("days.txt", "w")

days_file.seek(0,2)


days_file.write(" Saturday\n Sunday")

days_file.close()

# Re open file in read mode, read the file, print list of both old and new data

days_file = open("days.txt", "r")

days_file.seek(0)


days = days_file.read()


print("My output is: \n",day)

My output is: 
  Saturday
  Sunday

I can get this code work if I don't close the file at any point, and just stay in w+ mode, however, what I am searching for is a way to create + write + close + reopen + append. Any solutions?

Gino
  • 1,043
  • 16
  • 27

1 Answers1

2

Use file = open("days.txt", "a") to open a file in append mode

EDIT:

Opening a file with the with keyword allows for safe and consistent closing of files, even if an Exception is thrown.

with open(myfile, 'w+'):
    # Do things

# File closes automatically here

Otherwise, you have to manually call file.close(). Without that, your file will remain open, and if you are constantly opening files, you can run out of handles

C.Nivs
  • 12,353
  • 2
  • 19
  • 44