text file to array and back

Andreas Kremer andreas3004 at hotmail.com
Sat Mar 17 14:57:51 EST 2001


Hi,

i am trying to write a python class to make access to a collection of
scientific analysis programs easier for me. In this case I need to read a
file which consists of a time series, collect it into an array (numpy
preferred) and after some operations write it back to disk as a text file.
My solutions are attached. These are my questions:
1. as I am new to python i suspect my joining and splitting not to be very
efficient, especially the joining. 2. Is there a way while reading the file
to store the data immediately into the array?
3. I am concerned about a memory leak. what happens to self.array if I read
the file again? It obviously doesnt append the data to the old, but are the
old data deleted from the memory?

Thanks in advance. Andreas Kremer.

    def __createarray(self):
        "creates an array of the outputfile"
        # open file, transfer content into list self.array
        file = open(self.outputfile, 'r')
        for line in file.readlines():
            dataline = map(float, string.split(line))
            self.array.append(dataline)
        file.close()
        # convert list self.array into an array (Numpy)
        self.array = array(self.array, Float64)

    def __writearray(self):
        "writes array to outputfile"
        # open file, format array and write it to disk
        file = open(self.outputfile, 'w')
        for line in self.array:
            dataline = string.join(str(line),'')
            dataline = dataline+'\n'
            dataline = string.replace(dataline,'[','')
            dataline = string.replace(dataline,']','')
            dataline = string.replace(dataline,',','')
            file.write(dataline)
        file.close()





More information about the Python-list mailing list