{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from __future__ import print_function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One of the main things that we want to do in scientific computing is get data into and out of our programs. In addition to plain text files, there are modules that can read lots of different data formats we might encounter." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Print" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We've already been using print quite a bit, but now we'll look at how to control how information is printed. Note that there is an older and newer way to format print statements -- we'll focus only on the newer way (it's nicer).\n", "\n", "This is compatible with both python 2 and 3" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = 1\n", "y = 0.0000354\n", "z = 3.0\n", "s = \"my string\"\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We write a string with `{}` embedded to indicate where variables are to be inserted. Note that `{}` can take arguments. We use the `format()` method on the string to match the variables to the `{}`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(\"x = {}, y = {}, z = {}, s = {}\".format(x, y, z, s))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Before a semi-colon, we can give an optional index/position/descriptor of the value we want to print.\n", "\n", "After the semi-colon we give a format specifier. It has a number field and a type, like `f` and `g` to describe how floating point numbers appear and how much precision to show. Other bits are possible as well (like justification). " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(\"x = {0}, y = {1:10.5g}, z = {2:.3f}, s = {3}\".format(x, y, z, s))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "there are other formatting things, like justification, etc. See the tutorial" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(\"{:^80}\".format(\"centered string\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# File I/O" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "as expected, a file is an object. Here we'll use the `try`, `except` block to capture exceptions (like if the file cannot be opened). " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "f = open(\"./sample.txt\", \"w\")\n", "print(f)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "f.write(\"this is my first write\\n\")\n", "f.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "we can easily loop over the lines in a file" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "f = open(\"./test.txt\", \"r\")\n", "\n", "for line in f:\n", " print(line.split())\n", " \n", "f.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "as mentioned earlier, there are lots of string functions. Above we used `strip()` to remove the trailing whitespace and returns" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# CSV Files" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "comma-separated values are an easy way to exchange data -- you can generate these from a spreadsheet program. In the example below, we are assuming that the first line of the spreadsheet/csv file gives the headings that identify the columns. \n", "\n", "Note that there is an amazing amount of variation in terms of what can be in a CSV file and what the format is -- the csv module does a good job sorting this all out for you." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import csv\n", "\n", "reader = csv.reader(open(\"shopping.csv\", \"r\"))\n", "\n", "headings = None\n", "\n", "items = []\n", "quantity = []\n", "unit_price = []\n", "total = []\n", "\n", "for row in reader:\n", " if headings == None:\n", " # first row\n", " headings = row\n", " else:\n", " items.append(row[headings.index(\"item\")])\n", " quantity.append(row[headings.index(\"quantity\")])\n", " unit_price.append(row[headings.index(\"unit price\")])\n", " total.append(row[headings.index(\"total\")])\n", " \n", "\n", "for i, q in zip(items, quantity):\n", " print (\"item: {}, quantity: {}\".format(i, q))\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.3" } }, "nbformat": 4, "nbformat_minor": 0 }