I’m using Python 3.2 and the configparser module, and running into some problems. I need to read, then write to a config file. I tried the following:
import configparser
data = open('data.txt', 'r+')
a = configparser.ConfigParser()
a.read_file(data)
a['example']['test'] = 'red'
a.write(data)
The problem is that when I open data with r+, when I write to it the new information gets appended; it does not overwrite the old.
import configparser
data = open('data.txt', 'r')
a = configparser.ConfigParser()
a.read_file(data)
a['example']['test'] = 'red'
data = open('data.txt', 'w')
a.write(data)
This way ^ seems unsafe, because opening it with w empties the file. What if the program crashes before it has time to write? The configuration file is lost. Is the only solution to backup before opening with w?
Edit:
The following is also a possibility, but is it safe?
a.write(open('data.txt','w'))
If you’re really concerned about that, you can write to a temporary file, and then rename the temporary file to this one — if the config write fails, the original will be untouched; rename/move is usually atomic (though under Windows you might need to call
MoveFileExdirectly, instead of usingos.rename), so you can be sure that you’ll either have the old contents or the new contents, and the file won’t be in any other state (sans any critical failures of the underlying filesystem, of course).