reading numbers from file
Neelakantan Krishnaswami
neelk at alum.mit.edu
Thu Dec 21 21:40:31 EST 2000
On 22 Dec 2000 00:27:06 GMT, Jacek Pop³awski <jp at ulgo.koti.com.pl> 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...])
This code will put a big list of numbers into the array allnums
import string
def string_to_numbers(line):
return map(int, string.split(line))
allnums = []
file = open("foo.txt")
for line in file.readlines():
numbers_on_line = string_to_numbers(line)
allnums.extend(numbers_on_line)
The function string_to_numbers can also be written in two other
ways:
def string_to_numbers(line):
return [int(x) for x in string.split(line)]
def string_to_numbers(line):
lst = []
for x in string.split(line):
lst.append(int(x))
return lst
Any of these is fine -- use whichever is most clear to you.
> 2.How to read only 5 numbers, write it to list, then another 5, and
> write it to second list?
lst1 = []
lst2 = []
file = open("foo.txt")
current = lst1
count = 1
for line in file.readlines():
numbers_on_line = string_to_numbers(line)
#
# Each number should be written to either lst1 or lst2. We'll
# track the number of numbers written to both lists and flip
# to the other one each time we hit a multiple of 5.
#
for n in numbers_on_line:
current.append(n)
count = count + 1
if (count % 5) == 0:
if current == lst1:
current = lst2
else:
current = lst1
> 3.What will change if I want to add comments (#) and empty lines to
> my file?
You'll need to change the function string_to_numbers() so that it can
account for these two changes to your format. string.split() already
returns an empty list if it receives a line of whitespace, so it
already works on blank lines. To handle '#' to the end of line
comments, we can either use regexps or string.split() again. I'll do
both.
The basic idea is that if we do string.split on '#' then we get a list
of elements that are divided by the '#'. We only need to look at the
first element of that list since it is the string that precedes the
first '#' on the line.
def string_to_numbers(line):
comment_free_line = string.split(line, "#")[0]
return map(int, string.split(comment_free_line))
# And then the prior solutions follow.
Using regexps, the solution might look like this:
import re
comment_free = re.compile("^([^#]*).*$")
def string_to_numbers(line):
m = comment_free.match(line)
comment_free_line = m.group(1)
return map(int, string.split(comment_free_line))
I hope this helped.
Neel
More information about the Python-list
mailing list