将数组写入CSV文件 [英] Writing an array to a CSV file
问题描述
我试图创建一个数组并将其输出到具有正确行和列的excel。但是当我运行下面的代码时,它会将它们全部列在一列和16行中。任何方式我可以改变它,以它给我4列和4行?
I a trying to create an array and output it to an excel with the correct rows and columns. But when I run the code below, it gives me them in all in one column and 16 rows. Any way i can change it so that it gives it to me in 4 columns and 4 rows?
do i = 1, 4
do j = 1, 4
test(i,j) = 2
print *, test(i,j)
open( unit = 10, file = "test.csv")
write(10,*), test(i,j)
end do
end do
推荐答案
有些事情首先:如果你做文件i / o,你需要打开和关闭文件。你只需要这样做一次。
Some things first: If you do file i/o, you need to open and close the file. You only need to do this once.
接下来,每个写入
语句将(除非另有明确说明),提前
Next, each write
statement will (unless explicitly stated otherwise), advance the line.
获得您想要的最简单的方法是:
The easiest way to get what you seem to want is this:
test(:, :) = 2
open(unit=10, file='test.csv')
do j = 1, 4
write(10, *) test(1:4, j)
end do
close(10)
但这不是逗号分隔。假设 test
是一个整数数组,您可以修改上面的写入
语句:
But this is not comma separated. Assuming that test
is an integer array, you could modify the write
statement above to this:
write(10, '(3(I0, ", "), I0)') test(1:4, j)
更新:我刚刚确认了@ mark-s的建议:
Update: I just confirmed @mark-s suggestion:
write(10, '(*(I0 : ", "))') test(:, j)
这更好,因为你不必知道数组的大小。
This is even better as you don't have to know the size of the array.
或者甚至更好,并描述了这里,你可以使用 CSV模块
Or, even better, and described here, you could use a CSV module
这篇关于将数组写入CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!