Oddie
Oddie

Reputation: 71

Read data from a .csv file in fortran

I am using a software that gives me as an output a .csv file which I want to read with the aid of a fortran code. The .csv file has the following form :

balance for 1. Unit: kg N/ha
___________________________________________________________________________________________________________________________________________________________________________
,N Pools,,,,,Influx N,,,,,Efflux N
Day,iniSON,iniSIN,endSON,endSIN,dSoilN,Deposit,Fertilizer,Manure,Litter,Sum-In...(**20 parameters**)
___________________________________________________________________________________________________________________________________________________________________________
 1,5973.55,  20.20,5973.51,  20.23,  -0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,  -0.00,   0.00
.........

I have 365 lines with such values.

Example

In order to read the first lines I used the following :

program od

implicit none
integer :: res
character(LEN=200) :: head1,head2,head3,head4,head5
open(10, file="Balance_N_1.csv",access='sequential',form="formatted",iostat=res)
open(9,file="out.txt")
read(10,fmt='(A)', iostat=res) head1,head2,head3,head4,head5
write(9,*) head1,head2,head3,head4,head5       

end program od

How is it possible to read the data that follow and to put them in a matrix so that I can perform calculations with some of the values?

Upvotes: 7

Views: 20176

Answers (1)

High Performance Mark
High Performance Mark

Reputation: 78316

If I read your question right you have a file with 365 lines of data, each line has 1 integer (the day number) and 20 real numbers and the values on each line are comma-separated. You could declare a data array like this;

real, dimension(365,20) :: data_array

and an integer variable such as

integer :: line_no

then, once you've read, or skipped over, the lines of text at the top of your file, you can read the array like this:

do ix = 1,365
    read(10,*) line_no, data_array(ix,:)
end do

By using * for the format in your read statement you are using list-directed input which is quick and easy but somewhat limited. However, if your data file is clean and consistent this should be good enough.

If list-directed input doesn't work you'll have to use edit descriptors, something like this (untested)

read(10,'(i4,20f9.4)') line_no, data_array(ix,:)

Upvotes: 10

Related Questions