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'))