{ "cells": [ { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "# Reading and Writing Data Files with Python" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "In order plot or fit data with Python, you have to get the data into the program. If a program makes calculations using data, it can be useful to write the results to a file." ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "## 1. Reading Data Files" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "In Python, it is often useful for data to be in arrays. Data can be entered directly into the programs using the **`array`** function from the numpy library. For instance, the following lines assign arrays of numbers to `x`, `y`, and `yerr`." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ ], "source": [ "from numpy import *\n", "\n", "x = array([0.0, 2.0, 4.0, 6.0, 8.0]) \n", "y = array([1.1, 1.9, 3.2, 4.0, 5.9]) \n", "yerr = array([0.1, 0.2, 0.1, 0.3, 0.3])" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "However, this is not a good way to handle large data sets. It is better to store the data in a separate file and have the program read the data file. You could use a text editor (*Idle* works well or you can create and edit a file in *CoCalc*) to enter the data above in the form shown below. The values of `x`, `y`, and `yerr` (the uncertainty in `y`) for a single data point are entered on the same line separated by spaces or tabs.\n", "