Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

savetxt & close file + python + numpy

I was wondering if anyone could help me with one problem that I have when using the python + numpy function 'savetxt'.

The problem is:

(1) I have a subroutine in which I save a matrix (numerical data) into a textfile (using the function savetxt):

For example:

import numpy as np
A = np.matrix('1 2; 3 4')
np.savetxt('myfile.txt', A, fmt='%-7.8f', delimiter=',')

(2) Then, I have to use that data in another program. It is a time-domain simulation and I need to read the data at each iteration. I observe the following:

  • Reading the data from the file that I have created makes the process much more slower.

  • The curious thing is that, if I use the same data (without saving it before with my subroutine), the program goes fast. For example, if I save the data, it goes slow, but if I restart the computer, it goes fast.

Perhaps the file is not closed when I use it later.

I would be very grateful if someone can give me some clues about possible causes of this problem.

Thank you very much.

Javier

like image 354
javierr271828 Avatar asked Apr 15 '26 07:04

javierr271828


1 Answers

I doubt that the savetxt method does not close the file at the end. Anyway, to be sure, you can save your file this way:

with open('myfile.txt', 'wb') as f:
    np.savetxt(f, A, fmt='%-7.8f', delimiter=',')

In which case you are sure that the file is closed afterwards.

like image 169
Taha Avatar answered Apr 16 '26 21:04

Taha