Attached are a config file parser that i'm working on, and a example config file. Basically, what my problem is is in write_config, it should search through the file, and replace the lines with whatever the modified version is, it is also designed to ignore comments. To see my problem (which is hard to describe) please first look at the config file, and then run config-parse.py then look at the config file again. One of two things should happen: nothing, or something weird should happen on the last line.
#!/usr/bin/python
import fileinput

def read_config(file):
	config={}
	if isinstance(file, type('str')) :
		config_file=open_config_file(file, 'r')
		if not config_file:
			return 1
		for option in config_file:
			option=option.replace('\n','')
			if option!='' and  '#' not in option:
				option=option.split(':') 
				config[option[0]]=option[1]
		config_file.close()
		return config
	else: 
		print "the file paramenter should be a string contianing a file path"
		return 1
	
def write_config(config, file):
	if isinstance(config, type({})) and isinstance(file, type('str')):
		config_file=open_config_file(file,'r+')
		if not config_file:
			return 1

		for line in config_file:
			line=line.replace('\n','')
			if line!='' and  '#' not in line:
				option=line.split(':')
				new_line = option[0]+':'+config[option[0]] + '\n'
				
				print config_file.write(line.replace(line, new_line))
		config_file.close()
	else:
		print "The config arg must be a dictionary and/or the file arg must be a string containing a file path"
def open_config_file(file, mode):
	try:
		config_file=open(file,mode)
	except IOError: 
		print "That File Doesn't exist!"
		return None
	return config_file
	
if __name__ == '__main__':
	file = './net-responsibility.conf2'
	config=read_config(file)
	print config
	config["logfile"]=' 5'
	file = './net-responsibility.conf2'
	write_config(config, file)
	
logfile: /var/log/example.log
pidfile: /var/run/example.pid
report_frequency: 7
online_user: Test
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to