Arun Padmanabhan
Arun Padmanabhan

Reputation: 45

Close a file without saving when an error occurs - Python

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

Upvotes: 1

Views: 835

Answers (2)

Barmar
Barmar

Reputation: 782407

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.

Upvotes: 2

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96277

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.

Upvotes: 1

Related Questions