[Tutor] Importing file data into Python arrays

alan.gauld@bt.com alan.gauld@bt.com
Tue, 28 May 2002 17:11:42 +0100


> import array
> arr=[]
> inp = open ("dat.txt","r")
> #read line into array
> for line in inp.readlines():
> 	arr.append(line)

You'd be as well to just copy readlines into arr...
readlines returns a list.

However I think you want to strip the line:

      line = line.strip()   # get rid of \n
      arr.append(line) 


> print arr [0:3]
> ['1 2 3\n', '4 5 6\n', '7 8 9']

So your lines consist of 3 numbers?
Are you trying to read in an array of single digits 
or an array of arrays each with 3 digits?

Assuming the former try this:

for line in f.readlines():
    line = line.strip() # get rid of \n
    nums = line.split() # separate the characters
    nums = map(int,nums) # convert to integers
    for n in nums: arr.append(n) # add to your array

If you want an (nx3) array just change the last line to

    arr.append(nums)

I suspect there are cleverer ways of doing this with 
less code but the above should be clear?

> num = int(string), but I the "/n" can't be dealt with 

Either string.strip() or string[:-1]

will remove the newline character.

HTH,

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld