[Tutor] newbie problems

Ivan Van Laningham ivanlan@callware.com
Fri, 02 Jul 1999 13:37:00 -0600


Hi Steve--

Stephen_Gilbert@npd.com wrote:
> 
> Help!
> 
> I'm trying to write a simple script to:
> 
>       open 2 files one new file for writing, one existing file to read
> from,
>       read a line at a time and write it to the new file,
>       if the first 3 bytes of the line is "+++"
>       then I want to take 5 bytes starting at position 15 and append it
> to the end of each line.
> 
> I have done this type of processing on many different platforms in the
> past, but now I need to do it using Python on Unix.
> I have figured out how to open the files and how to read each line into
> a string variable. However I can't figure out how to parse the variable
> and concatenate the new string to write out to the new file. Any help
> would be greatly appreciated.
> 
> TIA
> 
> Steve
> 

This is the sort of thing Python is *really* good at.  Assume s contains
your whole line:

plus = s[:3] #  Grab first three bytes; you can also write this as
s[0:3]
if plus == '+++':
	appnd = s[15:20]
	newline = s + appnd
	outfile.write(newline)
else:
	# do whatever you need to do if the first three chars aren't +++

Alternatively, you can dispense with the temporary variables:

if s[:3] == '+++':
	outfile.write(s + s[15:20])

and speed it up with a slight penalty in readability.

Look at the docs for slicing at www.python.org.

<it-slices-it-dices-operators-are-standing-by>-ly y'rs,
Ivan
----------------------------------------------
Ivan Van Laningham
Callware Technologies, Inc.
ivanlan@callware.com
ivanlan@home.com
http://www.pauahtun.org
See also: 
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
----------------------------------------------