reading numbers from file

Bjorn Pettersen pbjorn at uswest.net
Thu Dec 21 21:23:11 EST 2000


Here's a start. It only deals with comments when reading a line at a time, and I
haven't tested the edge cases, but it should at least get you going...

-- bjorn

import string

class NumberReader:
 def __init__(self, file):
  self.fp = file

 def readNumberLine(self):
  line = ''
  while 1:
   line = self.fp.readline()
   if not line:
    break
   if line.strip() == "":
    continue # skip empty lines
   if line.strip().startswith('#'):
    continue # skip comment lines
   return map(int, line.split())

 def readNumbers(self, n=5):
  res = []

  for i in range(n):
   word = ''

   # skip whitespace
   char = self.fp.read(1)
   while char in string.whitespace:
    char = self.fp.read(1)

   # read next word (number)
   while char not in string.whitespace:
    word += char
    char = self.fp.read(1)

   res.append(int(word))

  return res

def test():
 import StringIO
 f = StringIO.StringIO("""
 23 41 24 0 2 42 532 53 234
 34 234 53 23 4 323 53 345
 0 32 64 128 256 512 1024
 """)
 nr = NumberReader(f)
 a = nr.readNumberLine()
 print a
 print nr.readNumbers(3)
 print nr.readNumbers(5)

if __name__=="__main__":
 test()


Jacek Pop³awski wrote:

> I have file with numbers:
>
> 23 41 24 0 2 42 532 53 234
> 34 234 53 23 4 323 53 (etc...)
>
> 1.How to read one line of this file and write it to list of numbers?
>   (like: a=[23,41,24...])
> 2.How to read only 5 numbers, write it to list, then another 5, and write
>   it to second list?
> 3.What will change if I want to add comments (#) and empty lines to my file?
>
> --
> Don't care which God you follow
> Whose promises you swallow
> Time and again
> We must meet at the end              "Lord of the Last Day" - Ronnie James Dio




More information about the Python-list mailing list