Writing data to a file in Python

How can I save data to a file (which I will build later)?

I have this from my research:

#Open new data file f = open("data2.txt", "w") f.write( str(yEst) ) # str() converts to string f.close() 

Here is some of my code:

 for i in drange2(0, 2*math.pi + 0.0634665182543392 , 0.0634665182543392): for x in range(1,N+1): yEst = yEst + a * cos(x* i) #print yEst f.write( str(yEst) ) # str() converts to string yEst=0 f.close() 

Now when I open the file " data2.txt ", I can not read the data because it is not "organized". How can I go to the next line using f.write( str(yEst) ) so that I have a column containing my data "yEst" in the file "data2.txt"? Thank you in advance for your consideration :)

PS: yEst looks like (in data2.txt file): 48.901347147148.605785828748.114506165947.429486 .. and I want it to be like a column: โ†’

 48.9013471471 (new line) 48.6057858287 (new line) 48.1145061659 (new line) 47.4294863684 etc .. 
+6
source share
3 answers

You want to say that you need each data point in its own row?

 48.9013471471 48.6057858287 48.1145061659 47.4294863684 

If so, then you might like to try something like this:

 for i in drange2(0, 2*math.pi + 0.0634665182543392 , 0.0634665182543392): for x in range(1,N+1): yEst = yEst + a * cos(x* i) f.write( str(yEst) + "\n" ) f.close() 

First, to write each data point in a row, it must be "inside" the loop - so I added extra space to the row before I f.write .

The second thing I added is + "\n" - this will add a new line character to the end of the line. You can change it to whatever you want! A few examples:

f.write( str(yEst) + " " ) will add one place after each data point:

 48.9013471471 48.6057858287 48.1145061659 47.4294863684 

f.write( str(yEst) + "|" ) will add one channel character after each data point:

 48.9013471471|48.6057858287|48.1145061659|47.4294863684| 

If, on the other hand, you prefer to just save the data as an array, try the following:

 yEst = 0 # or some initial value yEstArray = [] for i in drange2(0, 2*math.pi + 0.0634665182543392 , 0.0634665182543392): for x in range(1,N+1): yEst = yEst + a * cos(x* i) yEstArray.append(yEst) 

Then you can iterate over the array this way:

 for yEst in yEstArray: do something with yEst 

or

 for yEst, index in enumerate(yEstArray): do something with yEst and its index 
+9
source

You will need pickle to serialize the data.

+4
source

Python has three main built-in ways to save data:

  • pickle , which serializes objects to files;
  • sqlite - built-in SQL database supported by many ORM systems (which with this add-on is an excellent alternative to pickle for storing objects); and
  • json / yaml - serialization designed for the Internet, with basic data structures and types.
+4
source

Source: https://habr.com/ru/post/923986/


All Articles