read lines
Neil Cerutti
horpner at yahoo.com
Tue Dec 4 08:20:28 EST 2007
On 2007-12-04, Horacius ReX <horacius.rex at gmail.com> wrote:
> Hi, I have a text file like this;
>
> 1 -33.453579
> 2 -148.487125
> 3 -195.067172
> 4 -115.958374
> 5 -100.597841
> 6 -121.566441
> 7 -121.025381
> 8 -132.103507
> 9 -108.939327
> 10 -97.046703
> 11 -52.866534
> 12 -48.432623
> 13 -112.790419
> 14 -98.516975
> 15 -98.724436
>
> So I want to write a program in python that reads each line and
> detects which numbers of the second column are the maximum and
> the minimum.
Check out 3.6.1 String Methods in the Python Library Reference.
It contains what you need.
Also, read about max and min from 2.1 Built-in Functions.
> I tried with;
>
> import os, sys,re,string
The string module is best avoided, except for a few character
classes, e.g., Paladins and Clerics. ;-) Use str methods instead.
It's more readable to import one module per line.
> # first parameter is the name of the data file
> name1 = sys.argv[1]
> infile1 = open(name1,"r")
>
> # 1. get minimum and maximum
>
> minimum=0
> maximum=0
>
>
> print " minimum = ",minimum
> print " maximum = ",maximum
>
>
> while 1:
> line = infile1.readline()
This isn't the best way to read files in Python. Check out 7.2
Reading and Writing Files in the Python Tutorial.
> ll = re.split("\s+",string.strip(line))
> print ll[0],ll[1]
> a=ll[0]
> b=ll[1]
Don't mix tabs and spaces. Python's Style Guide generally
recommends four spaces per indent.
> print a,b
> if(b<minimum):
readline returns str objects. You'll need to convert them to
numbers manually before comparing.
> minimum=b
> print " minimum= ",minimum
> if(b>maximum):
> maximum=b
> print " maximum= ",maximum
>
> print minimum, maximum
>
>
> But it does not work and I get errors like;
>
> Traceback (most recent call last):
> File "translate_to_intervals.py", line 20, in <module>
> print ll[0],ll[1]
> IndexError: list index out of range
This is caused by line becoming an empty string when readline
encounters end of the file.
> Could anybody help me ?
The following will not work in Python 2.4 or earlier.
from __future__ import with_statement
import sys
from operator import itemgetter
from contextmanager import closing
with closing(file(sys.argv[1])) as fp:
table = [(int(i), float(n)) for i, n in (line.split() for line in fp)]
print table
print "maximum =", max(table, key=itemgetter(1))
print "minimum =", min(table, key=itemgetter(1))
--
Neil Cerutti
More information about the Python-list
mailing list