What I want to do, is basically convert this Fortran code into Python:
open (1,file='file',form='formatted')
write (1,*) na,nb
write (1,*) (a(i),i=1,na)
write (1,*) (b(j),j=1,nb)
do i=1,na
write (1,*) (f1(i,j),j=1,nb)
write (1,*) (f2(i,j),j=1,nb)
enddo
So I thought about using savetxt. The first difficulty I found, was the first line, where na and nb should be save on the same line in the file. I've found that you can achieve this with:
np.savetxt("file.txt",(na,nb),fmt='%s',newline=" ")
The problem, is then whenever I want to write the second line as:
f=open("file.txt",'f')
np.savetxt(f,a,fmt='%s',newline=" ")
The array a gets added on the same line as na and nb, while I want it to be so on a new one. I can't figure out how to do this. I thought that with newline=" ", I just had to add " " to na,nb, but it doesn't work. Alternatively, what would be the cleanest way to write that Fortran code?
CodePudding user response:
Assuming you one one row on each line like
1.23 1.23 1.23 1.23
2.34 2.34 2.34 2.34
then something like this should work:
f = open('file.txt','w')
print(na, nb, file=f)
np.savetxt(f, a.reshape(1,na), fmt='%s', delimiter=' ')
np.savetxt(f, b.reshape(1,nb), fmt='%s', delimiter=' ')
for row in range(f1.shape[0]):
np.savetxt(f, f1[row], fmt='%s', delimiter=' ')
np.savetxt(f, f2[row], fmt='%s', delimiter=' ')
savetxt
puts one row on each line, but with a 1-D array, each element is considered a row. Thus, I reshape it to 2-D (reshape
costs almost nothing; it just changes the interpretation).