tags:

views:

97

answers:

3

Hello,

I am trying to write a python script

that takes record data like this

6xxxxxxxx
7xxxxxxxx
6xxxxxxxx
7xxxxxxxx
7xxxxxxxx
6xxxxxxxx
6xxxxxxxx
6xxxxxxxx
7xxxxxxxx
7xxxxxxxx
7xxxxxxxx

and performs the following logic

newline = ""
read in a record
    if the record starts with a 6 and newline = ''
     newline = record
    if the records starts with a 7
     newline = newline + record
    if the record starts with a 6 and newline != ''
     print newline
     newline = record

So it should print out like this:

6xxxxxx 7xxxxxxxx
6xxxxxx 7xxxxxxxx 7xxxxxxx 7xxxxxxx
6xxxxxx
6xxxxxx
etc..

Here is my code:

han1 = open("file","r")

newline = ""
for i in han1:
        if i[0] == "6" and newline == "":
                newline = i
        elif i[0] == "7":
                newline = newline + i
        elif i[0] == "6" and newline != "":
                print newline
                newline = ""
                newline = i


han1.close()

When I run my script the output looks untouched. Where do you think I'm going wrong. Is it because the newline variable won't store values between iterations of the loop? Any guidance would be appreciated.

A: 

None of the branches in your if statement finish with newline set to "". Therefore, the first branch will never evaluate because newline is never "" except for the very first case.

Mark Rushakoff
A: 

You can simplify this by simply appending a newline for a record that starts with 6, and not appending one if it doens't.

for line in open('infile'):
  if line[0] == '6':
    print ''
  print line.strip() ,

OK, this creates one empty line first in the file, and may not end the file with an newline. Still, that's easy to fix.

Or a solution that doens't have that problem and is closer to yours:

newline = ''
for line in open('infile'):
    if line[0] == '6':
        if newline:
            print newline
            newline = ''
    newline += ' ' + line.strip()
if newline:
     print newline

Also works, but is slightly longer.

That said I think your main problem is that you don't strip the records, so you preserve the line feed.

Lennart Regebro
A: 

if you file is not in GB,

data=open("file").read().split()
a = [n for n,l in enumerate(data) if l.startswith("6") ]        
for i,j in enumerate(a):
    if i+1 == len(a):
        r=data[a[i]:]
    else:
        r=data[a[i]:a[i+1]]
    print ' '.join(r)
ghostdog74