Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – saving data in a text file


Let's save the results of a calculation to a text file. In the next example, we will get the data back into Sage. When you enter the following code, change the path to the data file so that it gets saved in a convenient location.

from matplotlib import pyplot as plt
import os

# Create some data
times = srange(0.0, 10.0, 0.1)
data = [sin(t) for t in times]
    
# Plot the data
plt.figure(figsize=(6,4))
plt.plot(times, data)
plt.savefig('example2a.png')
plt.close()

# Save data to a text file
path = '/Users/cfinch/Documents/Writing/Sage for Beginners/Chapters/Chapter 4/'
fileName = 'data.txt'
text_file = open(os.path.join(path, fileName), 'w')
for i in range(len(data)):
    text_file.write('{0}, {1}{2}'.format(times[i], data[i], 
        os.linesep))
    
text_file.close()

Run the script using one of the methods previously described. A plot of the data is saved to a PNG file, and the data is saved to a text file with two columns. The plot should...