есть cnf-файл, хранящий различные настройки программы. В нем несколько секций с опциями:
[DataBase]
dbname = exper1
host = localhost
port = 5432
username = postgres
userpswd = 321
[PathToFiles]
path2prices = d:\csv\
path2sootv = d:\csv_tbl_sootvet\
path2reit = d:\reit\Рейтинг.DBF
[MinPrices]
path = d:\min_prices\
period = 7
[Dinam]
path = d:\dinam_prices\
period = 30
[VirtSum]
path = d:\dinam_prices_virt_sum\
period = 30
есть модуль, который позволяет править только настройки подключения к БД.
#!/usr/bin/env python
# -*- coding: cp1251 -*-
#форма для просмотра/сохранения настроек
import re, sys, os, datetime, time, distutils.file_util, distutils.filelist, csv, sqlite3, dbf_reader
from Tkinter import *
import tkMessageBox
import ConfigParser
SETTINGS_PATH=os.path.dirname(__file__)
sys.path.append(SETTINGS_PATH)
path2settings=os.path.join(SETTINGS_PATH, 'settings.conf')
print path2settings
def save_settings(event):
config=ConfigParser.SafeConfigParser()
## config.add_section('DataBase')
config.set('DataBase', 'dbname', ent_name.get())
config.set('DataBase', 'host', ent_host.get())
config.set('DataBase', 'port', ent_port.get())
config.set('DataBase', 'username', ent_user.get())
config.set('DataBase', 'userpswd', ent_psw.get())
with open(path2settings, 'a') as configfile: config.write(configfile)
def get_settings():
config=ConfigParser.RawConfigParser()
config.read(path2settings)
ent_name.insert(END, config.get('DataBase', 'dbname'))
ent_host.insert(END, config.get('DataBase', 'host'))
ent_port.insert(END, config.get('DataBase', 'port'))
ent_user.insert(END, config.get('DataBase', 'username'))
ent_psw.insert(END, config.get('DataBase', 'userpswd'))
for i in config.sections():
print i
for i in config.items(i):
print ' ', i
print '\n'
def mclose(event):
root.destroy()
root=Toplevel(Tk())
lbl_name=Label(root, text=u'Имя БД:')
ent_name=Entry(root, width=15)
lbl_host=Label(root, text=u'Хост:')
ent_host=Entry(root, width=15)
lbl_port=Label(root, text=u'Порт:')
ent_port=Entry(root, width=15)
lbl_user=Label(root, text=u'Имя пользователя:')
ent_user=Entry(root, width=15)
lbl_psw=Label(root, text=u'Пароль:')
ent_psw=Entry(root, width=15)
frm_btn=Frame(root)
btn_save=Button(frm_btn, text=u'Сохранить')
btn_save.bind('<Button-1>', save_settings)
btn_exit=Button(frm_btn, text=u'Отмена')
btn_exit.bind('<Button-1>', mclose)
# заполняем текущими значениями
get_settings()
#---- grids
lbl_name.grid(row=0, column=0, pady=5, sticky=E)
ent_name.grid(row=0, column=1, pady=5, padx=5)
lbl_host.grid(row=1, column=0, pady=5, sticky=E)
ent_host.grid(row=1, column=1, pady=5)
lbl_port.grid(row=2, column=0, pady=5, sticky=E)
ent_port.grid(row=2, column=1, pady=5)
lbl_user.grid(row=3, column=0, pady=5, sticky=E)
ent_user.grid(row=3, column=1, pady=5)
lbl_psw.grid(row=4, column=0, pady=5, sticky=E)
ent_psw.grid(row=4, column=1, pady=5)
frm_btn.grid(row=5, column=0, columnspan=2, pady=10, sticky=S+E)
btn_exit.pack({'side':'right'})
btn_save.pack({'side':'right', 'padx':10})
root.mainloop()
Проблема в том, что когда щелкаю кнопку сохранить, процедура save_settings сохраняет только настройки БД. Остальные настройки удаляет (просто перезаписывает файл заново, насколько я понимаю). Пробовал менять write с wb на ab - но результат не очень - он добавляет еще одну секцию с БД, а не перезаписывает. А мне нужно, что бы просто перезаписала нужную мне секцию. Вопрос: как все таки сделать, что бы перезаписывала нужную секцию?