Search code examples
pythonpandasnumpyload

How to read a fortran fort.# where # is a number file in python


I have an output from a fortran code that looks like this:

enter image description here

The results are stored in a fort.# where # is a number in general file. How can I load this file in python where each column is a different array or a column of a dataframe?

Code I am using but doesn't work:

import numpy as np
number_of_integers =1
with open(file_location,'r') as f:
    header = np.fromfile(f, dtype=np.int, count=number_of_integers)
    data = np.fromfile(f, dtype=np.float32)

I have also tried:

data  = np.fromfile(file_location,dtype = np.float32)
new_data = data.reshape() # something here but I can't read the shape

You can find the file here: https://drive.google.com/drive/folders/1ohC2sHxs2M211HxIHd7yH2_Y5l5c1pQA?usp=sharing


Solution

  • Assuming your files are all of the same format & you dont want the header then the following reads your file and puts it into a 2D numpy array,

    import numpy as np    
    
    my_data = []
    with open('fort.21') as fort:
        
        for idx, row in enumerate(fort):
            
            if idx > 0:
                row_split = row.split('  ')[1:]
                temp_list = [float(r_s) for r_s in row_split]
                my_data.append(temp_list)
                
    my_data = np.asarray(my_data)