{ "metadata": { "name": "", "signature": "sha256:61ba7fc12caccdde58e5c478fe47afe52c6e4084264f0cb759e096ea4f746518" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Chapter 22: File Operations" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Example canopen.c, Page 547" ] }, { "cell_type": "code", "collapsed": false, "input": [ "try:\n", " fname=raw_input()\n", " fp=open('noexist',r)\n", "except:\n", " print \"Can't be opened\"\n", "else:\n", " print \"Can be opened\"" ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "file\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "Can't be opened\n" ] } ], "prompt_number": 1 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Example fcopy.c, Page 568" ] }, { "cell_type": "code", "collapsed": false, "input": [ "try:\n", " s=raw_input(\"Source\")\n", " d=raw_input(\"Destination\")\n", " source_fp=open(s,'rb')\n", " dest_fp = open(d,wb)\n", "\n", " for line in source_fp.readlines():\n", " dest_fp.write(line) \n", "\n", " dest_fp.close()\n", " source_fp.close()\n", "except:\n", " print \"Can't be opened\"\n" ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Sourcef1\n" ] }, { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Destinationf2\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "Can't be opened\n" ] } ], "prompt_number": 1 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Example invclear.c, Page 574" ] }, { "cell_type": "code", "collapsed": false, "input": [ "NAME_LEN=25\n", "max_parts=100\n", "char name=None*(NAME_LEN+1)\n", "on_hand=list()\n", "try:\n", " fp=open('inventory.dat','r')\n", "except:\n", " print \"Cant open inventory file\"\n", "num_parts=fp.read()\n", "for i in range (num_parts):\n", " on_hand[i]=0\n", "fp.seek(0,0)\n", "fp.write(on_hand)\n", "fp.close\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }