[Tutor] print problem

Steven D'Aprano steve at pearwood.info
Sat Dec 4 04:05:47 CET 2010


Hs Hs wrote:
> hi I have a file and it is in chunks:
> I want to be able to select the number that follows 'Elution: '  where the line 
> startswith (TITLE)(say
> 72.958) and check if it is larger than my choice of number (say
> 71.4). If it is then I want to print chunk from BEGIN LINE to END
> LINE separated by one empty line.
> 
> I wrote the following script, when executed in IDEL or python mode, 

What is "python mode"? Do you mean the interactive interpreter?


> it works. however I use python test_script_test.py , I get name error:
> 
> could you please help me whats wrong here. 


> $ python test_script_test.py
> Traceback (most recent call last):
>   File "test_script_test.py", line 14, in <module>
>     newk = dat[mystartl:myfinish]
> NameError: name 'myfinish' is not defined
> 
> 
> In python mode:
>>>> f1 = open('test','r')
>>>> da = f1.read().split('\n')
>>>> dat = da[:-1]
>>>> mytimep = 71.4
>>>> for i in range(len(dat)):
> ...         if dat[i].startswith('BEGIN LINE'):
> ...                 mystartl = i
> ...         if dat[i].startswith('END LINE'):
> ...                 myfinish = i
> ...         if dat[i].startswith('Title'):
> ...                 col = dat[i].split(',')
> ...                 x= float(col[2].split()[1])
> ...                 if x > mytimep:
> ...                         newk = dat[mystartl:myfinish]
> ...                         for x in newk:
> ...                                 print x

This can fail because myfinish doesn't get defined until you see a line 
"END LINE". So if you have a file like this:

BEGIN LINE   <= defines "mystart"
Title ...    <= tries to use "mystart" and "myfinish"
END LINE     <= defines "myfinish"

the call to dat[mystartl:myfinish] fails because there is no myfinish.

The reason it works in IDLE and the Python interactive interpreter is 
that you must have already defined a myfinish variable previously.

Your code does way too much work manually instead of letting Python 
handle it. If you want to read lines from a file, just read them from a 
file. This should be close to what you want:

f1 = open('test','r')
mytimep = 71.4
flag = False
collected = [] # Hold collected lines as you see them.
for line in f1:
     line = line.rstrip()  # strip whitespace from the end of the line
     if line == "BEGIN LINE":
         flag = True  # start processing
         continue  # but not *this* line, start at the next line
     if line == "END LINE":
         flag == False
     if flag:
         # process the line
         if line.startswith('Title'):
             col = line.split(',')
             x = float(col[2].split()[1])
             if x > mytimep:
                 collected.append(line)

for line in collected:
     print line


-- 
Steven



More information about the Tutor mailing list