1

I have a situation where I have a file open using 'with'. I make some edits to the file and save it if the changes are successful. However whenever an error occurs during file handling, I want the file to be close without any changes done to the file. The with seem to overwrite the file and make the file empty.

Here is the code:

with open(path + "\\Config\\"+ filename, 'wb') as configfile:
     config.write(configfile)

I get the "a bytes-like object is required, not 'str'" error for the above code which is fine. But all the content from the file has been removed when the error occurs.

How can be explicitly say the code to not save the changes and revert to the content that was existing before the change was made?

I use active python 3.5

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172

2 Answers2

2

If you don't want to make any changes to the original file unless everything is successful, what you should do is write your output to a new file. Then when you're done, rename that file to the original file.

If an error happens, you can use try/except to catch the error and delete the temporary file before exiting.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Open in a different mode than w. Using 'w' will created if it does not exist, otherwise it truncates whatever is in the file already. Use 'a' instead, which does not truncate by default. However, note that the file cursor will be at the end of the file. You you actually want to overwrite if there is no error, you'll have to f.seek(0) then f.truncate() manually.

EDIT

Actually, it might be better to use r+, which will not truncate automatically either, and the stream is at the beginning of the file instead of the end (like it is with 'a'), so only a simple f.truncate() will be necessary. See your options here. Basically, you definitely don't want 'w' but either one of 'r+' or 'a' depending on precisely the behavior you want.

Community
  • 1
  • 1
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • 1
    Both of these solutions will still update the file, they just won't truncate it completely. But you'll end up with a mix of old and new data, which is probably just as bad. – Barmar May 17 '17 at 22:12
  • @Barmar I was answering on the assumption that the only operation was a single simple `write`, and the error occurs when attempting to `open`, but you are right, if you *really* want to only modify the file upon successfully exiting the `with` block, you'll have to do something like what your answer proposes. – juanpa.arrivillaga May 17 '17 at 22:15
  • True, your solution works for the simple application in the question. – Barmar May 17 '17 at 22:17