Looping over variable file names [duplicate]

2019-01-09 19:21发布

This question already has an answer here:

I am using Fortran to do calculation on huge data set which was split into many files. The names of the files are:

maltoLyo12per-reimage-set1.traj
maltoLyo12per-reimage-set2.traj
maltoLyo12per-reimage-set3.traj

The code I wrote to do the calculation is as below:

fileLoop: do j = 31, 34

 OPEN(unit=31,status='old',file=fileplace//'maltoLyo12per-reimage-set1.traj')
 OPEN(unit=32,status='old',file=fileplace//'maltoLyo12per-reimage-set2.traj')
 OPEN(unit=33,status='old',file=fileplace//'maltoLyo12per-reimage-set3.traj')
 OPEN(unit=34,status='old',file=fileplace//'maltoLyo12per-reimage-set4.traj')

 ... operation....

close (j)
end do fileLoop

During the run I want the code to open each file at a time and close them after finish calculation. But the above code will open all the files at once and close them one after one upon finish calculation.

So I tried to alter the code something like below:

fileLoop: do j = 31, 34

 OPEN(unit=j,status='old',file=fileplace//'maltoLyo12per-reimage-set1.traj')

close (j)
end do fileLoop

But here I am facing a problem with the file name. Each time the loop run, the file name doesn't change because of the phrase "set1" in the file name. I want the number in the file name to change like set1, set2, set3, etc., subsequently with file unit number 31,32,33,34, etc.

1条回答
对你真心纯属浪费
2楼-- · 2019-01-09 19:55

Something like this: (edited to have unit numbers 31 to 34, filenames 1 to 4.)

character (len=90) :: filename

fileLoop: do j = 31, 34

 write (filename, '( "maltoLyo12per-reimage-set", I1, ".traj" )' )  j - 30
 OPEN(unit=j,status='old',file=filename)

close (j)
end do fileLoop
查看更多
登录 后发表回答