How to read a data file

From KratosWiki
Jump to: navigation, search

In numerical analysis it is often useful, to print the most important output (results) into a text file in order to execute later specific data analyses. If the latters are done using python, it is necessary to define an easy procedure to get the data. Let's consider the data file 'pippo.txt', composed by six data columns:


       ...
       1.16 0.0 0.0 124.603504009 1316.72472011 1841.33830628
       1.17 0.0 0.0 316.106839428 1212.04264753 2078.91929319
       1.18 0.0 0.0 483.668415264 984.53477668 2257.00453915
       1.19 0.0 0.0 592.179848638 597.708354219 2682.47144417
       ...


Let's suppose that the first column contains tha values of A variable, the second one of B, the third of C, the fourth of D, the fifth of E and the sixth of F. In order to read them in python and store them in tuple elements, the following procedure can be written:


       import string
       pippo = open("/.../path_to_pippo/.../pippo.txt","r")
       A = []
       B = []
       C = []
       D = []
       E = []
       F = []
       while 1:
               field = string.split(pippo.readline())
               if not field:
                   break
               A.append(float(field[0]))
               B.append(float(field[1]))
               C.append(float(field[2]))
               D.append(float(field[3]))
               E.append(float(field[4]))
               F.append(float(field[5]))


Let's have a look line by line:


       import string 

In this line the module "string" is imported (this module shuold be one of python module).


       pippo = open("/.../path_to_pippo/.../pippo.txt","r")

This command define the "object" pippo as the function that opens the file "pippo.txt" in order to read data in it.


       A = []
       B = []
       C = []
       D = []
       E = []
       F = []

In these lines tuple elements to store data are created.


       while 1:
               field = string.split(pippo.readline())
               if not field:
                   break


This "while loop" will continue until an empty line is found in the data file. "field = string.split(pippo.readline())" means: form "pippo.txt" read the current line, split it when a white space is encountered and memorize all the obtained components, in a vector called field. At every step of the loop the reading procedure pass to the following line.


       A.append(float(field[0]))
       B.append(float(field[1]))
       C.append(float(field[2]))
       D.append(float(field[3]))
       E.append(float(field[4]))
       F.append(float(field[5]))

With these lines every read data is stored in the specific tuple.

Personal tools
Categories