replacing lines in a file

MRAB python at mrabarnett.plus.com
Wed Jan 26 18:49:00 EST 2011


On 26/01/2011 21:50, mpnordland wrote:
> 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
 > 	
Sometimes the function returns the config (a dict) and sometimes it
returns 1. The Pythonic way would be to raise an exception if there's
an error.

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

You're reading a line from the file and then writing the new line over
whatever follows it.

Suppose you have a file containing "123\n45\n678\n".

You open the file. You're at position 0.

You read the first line "123\n". You're now at position 4.

You write "XYZ\n". You're now at position 8.

The file now contains "123\nXYZ\n78\n".

You've just overwritten the second line and part of the third 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)




More information about the Python-list mailing list