Tab delimited file

Tim Chase python.list at tim.thechases.com
Fri Aug 11 11:24:06 EDT 2006


> However as far as I know Python does not allow you to easily change a
> specific line in a text file. You have to place the whole file to memory,
> change what you need to and then write the file back after deleting the
> previous information. 
> 
> Assuming this is true, how do i find where the tabs are in the file so that
> I can distinguish between the different criteria? 


Well, I usually just use something like

NAME = 0
RATING = 1
SIZE = 2
OCCURS = 3
name = 'foo'
out = file('output.txt', 'w')
for line in file('input.txt'):
	line = line.rstrip('\n')
	items = line.split('\t')
	# do something with items:
	if name in items[NAME].lower():
		items[RATING] = str(int(items[RATING]) + 1)
	out.write('\t'.join(items))
	out.write('\n')

which will loop through each line, incrementing the RATING field 
(assuming it's numeric?) where the NAME field contains 'foo'; 
then writing the resulting stuff back out to the output file.

-tkc






More information about the Python-list mailing list