我正在尝试阅读看起来像这样的数据集
DATE,TIME,val
1/1/2001,1:00:00,0
程序
program main
implicit none
real :: val
character(len=8) :: date
character(len=7) :: time
open(1,file='data.csv',status='old')
read(1,*) ! header
read(1,fmt=100)date,time,val
100 FORMAT (A,1x,A,1x,F3.1)
end program
如果日期和时间总是有8或7个字符但是它们没有例如
4/21/2001,19:00:00,0
如何声明fortran的格式以读取示例中的日期,时间,val行?
谢谢
答案 0 :(得分:7)
您可以将所有整个data, time, value
行读入单个字符串,然后处理该行以提取单个元素,这些内容与
program main
implicit none
real :: val
character(len=10) :: date
character(len=8) :: time
character(len=100) :: line
integer :: n1, n2, end
open(1, file='data.csv', status='old')
! Read entire second line into `line`, ignoring the header
read(1,*) ! header
read(1,'(A100)') line
! Determine locations of the first and last comma in `line` and the
! end of the line:
n1 = index(line, ',')
n2 = index(line, ',', back=.True.)
end = len_trim(data)
! Split line up according to position of commas and assign to
! appropriate variables
date = data(1:n1-1)
time = data(n1+1:n2-1)
read(data(n2+1:end), *) val ! Internal read, for converting from string to float
end program main
请注意,这对于问题中的示例数据非常专业,但是对于此代码的概括应该不会太难。
答案 1 :(得分:0)
您尚未定义您正在使用的“数据”变量。此解决方案的另一个问题是,现在您将所有变量作为字符停留,这可能对分析无用。