{ "metadata": { "name": "Chapter11" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": "Chapter 11, Files" }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": "Example 1, Page Number:CP-277" }, { "cell_type": "code", "collapsed": false, "input": "# Program to create a text file\n\nfp = open(\"sample.txt\",\"w\") # open file in write mode\n\nprint \"Type the text and Press enter key at end.\"\nprint\nprint \"Computer Programming in C language is widely used for Science and Engineering applications\"\n# input data to file\nch = ['Computer ','Programming ','in ','C ','language ','is ','widely ','used ','for ','Science ','and ' ,'Engineering ','applications.']\nfor i in ch:\n fp.write(i)\nfp.close()\n ", "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": "Type the text and Press enter key at end.\n\nComputer Programming in C language is widely used for Science and Engineering applications\n" } ], "prompt_number": 1 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": "Example 2, Page Number:CP-278" }, { "cell_type": "code", "collapsed": false, "input": "# Program to read text file and count number of vowels\n\nfp = open(\"sample.txt\",\"r\") # open file in read mode\ncount = 0\nprint \"The Content of the file is:\"\n\nwhile (1): \n ch = fp.read(1)\n if not ch:\n break\n print ch\n # switch statements\n if ch == \"A\" or ch == \"a\": # case 'A' or 'a'\n count = count + 1\n elif ch == \"E\" or ch == \"e\": # case 'E' or 'e'\n count = count + 1\n elif ch == \"I\" or ch == \"i\": # case 'I' or 'i'\n count = count + 1\n elif ch == \"O\" or ch == \"o\": # case 'O' or 'o'\n count = count + 1\n elif ch == \"U\" or ch == \"u\": # case 'U' or 'u'\n count = count + 1\n\n\n\nfp.close() \nprint \"Number of vowels present =\",count \n ", "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": "The Content of the file is:\nC\no\nm\np\nu\nt\ne\nr\n \nP\nr\no\ng\nr\na\nm\nm\ni\nn\ng\n \ni\nn\n \nC\n \nl\na\nn\ng\nu\na\ng\ne\n \ni\ns\n \nw\ni\nd\ne\nl\ny\n \nu\ns\ne\nd\n \nf\no\nr\n \nS\nc\ni\ne\nn\nc\ne\n \na\nn\nd\n \nE\nn\ng\ni\nn\ne\ne\nr\ni\nn\ng\n \na\np\np\nl\ni\nc\na\nt\ni\no\nn\ns\n.\nNumber of vowels present = 31\n" } ], "prompt_number": 2 } ], "metadata": {} } ] }