I’m learning PyGTK and I’m making a Text Editor (That seems to be the hello world of pygtk :])
Anyways, I have a “Save” function that writes the TextBuffer to a file. Looks something like
try:
f = open(self.working_file_path, "rw+")
buff = self._get_buffer()
f.write(self._get_text())
#update modified flag
buff.set_modified(False)
f.close()
except IOError as e:
print "File Doesnt Exist so bring up Save As..."
......
Basically, if the file exist, write the buffer to it, if not bring up the Save As Dialog.
My question is: What is the best way to “update” a file. I seem to only be able to append to the end of a file. I’ve tried various file modes, but I’m sure I’m missing something.
Thanks in advance!
At the point where you write to the file, your location is at the end of the file, so you need to seek back to the beginning. Then, you will overwrite the file, but this may leave old content at the end, so you also need to truncate the file.
Additionally, the mode you’re specifying (
'rw+') is invalid, and I get IOErrors when I try to do some operations on files opened with it. I believe that you want mode'r+'(“Open for reading and writing. The stream is positioned at the beginning of the file.”).'w+'is similar, but would create the file if it didn’t exist.So, what you’re looking for might be code like this:
However, you may want to modify this code to correctly catch and handle errors while truncating and writing the file, rather than assuming that all IOErrors in this section are non-existant-file errors from the call to open.