How to import array from a file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • coolindienc
    New Member
    • Aug 2006
    • 48

    How to import array from a file

    I got this program that will prompt the user to enter the number. I want to import a file and have it filled. How do I do that?

    Code:
    from numarray import *
    
    def clrscr():
        print '\n'*50
        return
    
    def pressenter():
        raw_input('Press the enter key to continue')
        return
    
    prompt=['Enter row first number ', 'Enter row second number ']
    
    clrscr()
    
    rows=int(raw_input('Enter the number of rows in the array '))
    print
    cols=3
    print;print
    
    marray=zeros([rows,cols],type='f')
    
    for row in range(0,rows,1):
        for col in range(0,cols-1,1):
            marray[row,col]=float(raw_input(prompt[col]))
            print
    
    for row in range(0,rows,1):
        marray[row,2]=marray[row,0]*marray[row,1]
    
    for row in range(0,rows,1):
        print marray[row,0],marray[row,1],marray[row,2]
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    First you need a file (say) arrays.txt which has KNOWN GOOD data in it (it is easy to protect yourself from erronious data, but I'll keep this simple). Like:
    12,34 23.34 34.45
    45.56 56.67 78.99
    then you need to open that file:
    Code:
    arrayFile = open('arrays.txt')    # get file object
    In order to dimension the array statically, you'll need the number of lines in the file and you need the lines later, so you might as well make it into a list:
    Code:
    arrayList = arrayFile.readlines()
    arrayFile.close()
    nRows = len(arrayList)    # now you can dimension your array from nRows
    for i, row in enumerate(arrayList):
        floatList = [float(f) for f in row.split()]    # can be tabs or spaces. newlines are stripped off
        for j, float in enumerate(floatList):
            array(i,j) = float
    That's the basics. There are better way and this has not been tested. See if you can make it work with your arrays.

    Comment

    Working...