{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Chapter 12: Working with Files" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Program 12.1, page no. 498" ] }, { "cell_type": "code", "collapsed": false, "input": [ "\"\"\"\n", "Writing a file a character at a time\n", "\"\"\"\n", "\n", "import sys\n", "\n", "\n", "mystr = []\n", "\n", "print \"Enter an interesting string of up to 80 characters: \",\n", "mystr = raw_input()\n", "\n", "try:\n", " fp = open(\"myfile.txt\", \"w\")\n", "except:\n", " print \"error opening the file...\"\n", " sys.exit()\n", "\n", "for i in range(len(mystr)-1, -1, -1):\n", " fp.write(mystr[i])\n", "\n", "fp.close()\n", "\n", "try:\n", " fp = open(\"myfile.txt\", \"r\")\n", "except:\n", " print \"error opening the file...\"\n", "\n", "print \"the data read from the file is: \"\n", "while(True):\n", " c = fp.read(1)\n", " if not c:\n", " break\n", " print c,\n", "fp.close()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Enter an interesting string of up to 80 characters: " ] }, { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Too many cooks spoil the broth.\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ " the data read from the file is: \n", ". h t o r b e h t l i o p s s k o o c y n a m o o T\n" ] } ], "prompt_number": 13 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Program 12.2, page no. 502" ] }, { "cell_type": "code", "collapsed": false, "input": [ "\"\"\"\n", "As the saying goes. . .it comes back!\n", "\"\"\"\n", "\n", "proverbs = [\"Many a mickle makes a muckle.\\n\",\n", " \"Too many cooks spoil the broth.\\n\",\n", " \"He who laughs last didn't get the joke in the first place.\\n\"]\n", " \n", "more = []\n", "\n", "try:\n", " fp = open(\"myfile.txt\", \"w\") \n", "except:\n", " print \"error opening the file...\"\n", "for proverb in proverbs:\n", " fp.write(proverb)\n", "fp.close()\n", " \n", "fp = open(\"myfile.txt\", \"a\")\n", " \n", "print \"Enter proverbs of up to 80 characters (separated by '.') or press Enter to end:\\n\",\n", "string = raw_input().split('.')\n", "\n", "\n", "for str in string:\n", " fp.write(str+\"\\n\")\n", "fp.close()\n", "\n", "fp = open(\"myfile.txt\", \"r\")\n", "print \"The proverbs in the file are: \\n\"\n", "while(True):\n", " line = fp.readline()\n", " if not line:\n", " break\n", " print line\n", "fp.close()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Enter proverbs of up to 80 characters (separated by '.') or press Enter to end:\n" ] }, { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Every dog has his day. Least said, soonest mended. A stitch in time saves nine. Waste not, want not.\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "The proverbs in the file are: \n", "\n", "Many a mickle makes a muckle.\n", "\n", "Too many cooks spoil the broth.\n", "\n", "He who laughs last didn't get the joke in the first place.\n", "\n", "Every dog has his day\n", "\n", " Least said, soonest mended\n", "\n", " A stitch in time saves nine\n", "\n", " Waste not, want not\n", "\n", "\n", "\n" ] } ], "prompt_number": 3 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Program 12.3, page no. 507" ] }, { "cell_type": "code", "collapsed": false, "input": [ "\"\"\"\n", "Messing about with formatted file I/O\n", "\"\"\"\n", "\n", "import sys\n", "\n", "num1 = 234567\n", "num2 = 345123\n", "num3 = 789234\n", "\n", "ival = []\n", "\n", "try:\n", " fp = open(\"myfile.txt\", \"w\")\n", "except:\n", " print \"Error opening file for writing. Program terminated.\\n\"\n", " sys.exit()\n", "\n", "fp.write(\"%6d %6d %6d\" %(num1, num2, num3))\n", "fp.close()\n", "print \"%6ld %6ld %6ld\" %(num1, num2, num3)\n", "\n", "try: \n", " fp = open(\"myfile.txt\", \"r\")\n", "except:\n", " print \"Error opening file for reading. Program terminated.\\n\"\n", " sys.exit()\n", "\n", "line = fp.readline()\n", "line_split = line.split(\" \")\n", "num4 = int(line_split[0])\n", "num5 = int(line_split[1])\n", "num6 = int(line_split[2])\n", "print \"%6ld %6ld %6ld \" %(num4, num5, num6)\n", "fp.close\n", "\n", "fp = open(\"myfile.txt\", \"r\")\n", "line = fp.readline()\n", "line_join = \"\".join(line_split)\n", "ival.append(int(line_join[0:2]))\n", "ival.append(int(line_join[2:5]))\n", "ival.append(int(line_join[5:8]))\n", "ival.append(int(line_join[8:11]))\n", "ival.append(int(line_join[11:13]))\n", "ival.append(int(line_join[13:15]))\n", "fnum = (float(line_join[15:]))\n", "\n", "for i in range(len(ival)):\n", " print \"%sival[%d] = %d\" %((\"\\n\\t\" if i == 4 else \"\\t\"), i, ival[i]),\n", "print \"\\nfnum = %f \" %fnum" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "234567 345123 789234\n", "234567 345123 789234 \n", "\tival[0] = 23 \tival[1] = 456 \tival[2] = 734 \tival[3] = 512 \n", "\tival[4] = 37 \tival[5] = 89 \n", "fnum = 234.000000 \n" ] } ], "prompt_number": 4 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Program 12.4, page no. 514" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Program 12.4, page no. 514\n", "\n", "\"\"\"\n", "A prime example using binary files\n", "\"\"\"\n", "\n", "import math\n", "import sys\n", "\n", "MEM_PRIMES = 10\n", "PER_LINE = 8\n", "filename = \"myfile.bin\"\n", "fp = None\n", "primes = [2, 3, 5]\n", "count = 3\n", "\n", "def check(buff, count, n):\n", " root_N = (1.0 + math.sqrt(n))\n", " for i in range(0, count):\n", " if(n % buff[i] == 0):\n", " return 0\n", " if(buff[i] > root_N):\n", " return 1\n", " return -1\n", "\n", "def list_array():\n", " global primes\n", " global count\n", " for j in range(count):\n", " print \"%10lu\" %primes[j]\n", " if(((j + 1) % PER_LINE) == 0):\n", " print \"\\n\"\n", " \n", "def list_primes():\n", " global fp\n", " global filename\n", " global count\n", " global primes\n", " if(fp):\n", " try:\n", " fp = open(filename, \"rb\")\n", " except:\n", " print \"Unable to open %s to read primes for output \" %filename\n", " sys,exit()\n", " while(True):\n", " line = fp.readline()\n", " if line:\n", " list_array()\n", " print \"\\n\"\n", " fp.close()\n", " else:\n", " list_array()\n", "\n", "def write_file():\n", " global fp\n", " global filename\n", " global count\n", " global primes\n", " try:\n", " fp = open(filename, \"ab\")\n", " except:\n", " print \"Unable to open %s to append\\n\" %filename\n", " sys.exit()\n", " for prime in primes:\n", " fp.write(prime+\" \")\n", " fp.close\n", " count = 0\n", "\n", "def is_prime(n):\n", " global filename\n", " global fp\n", " global primes\n", " global count \n", " buff = []\n", " count = 0\n", " k = 0\n", " if(fp):\n", " try:\n", " fp = open(filename, \"rb\")\n", " except:\n", " print \"Unable to open %s to read. \" %g.filename\n", " sys.exit()\n", " while(True):\n", " line = fp.readline()\n", " if line:\n", " nums = line.split(\" \")\n", " for num in nums:\n", " buff.append(int(num))\n", " k = check(buff, count, n)\n", " if(k == 1):\n", " fp.close()\n", " return True\n", " else: \n", " break\n", " fp.close()\n", " return 1 == check(primes, count, n)\n", "\n", "trial = primes[count - 1]\n", "num_primes = 3\n", "\n", "print \"How many primes would you like? \",\n", "total = int(raw_input())\n", "total = 4 if total < 4 else total\n", "print total\n", "while(num_primes < total):\n", " trial += 2\n", " if(is_prime(trial)):\n", " primes.append(trial)\n", " count += 1\n", " num_primes += 1\n", " if(count == MEM_PRIMES):\n", " write_file()\n", "\n", "if(fp and count > 0):\n", " write_file()\n", "list_primes()" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 11 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Program 12.5, page no. 523" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Program 12.5, page no. 523\n", "\n", "\"\"\"\n", "Investigating the family.\n", "\"\"\"\n", "\n", "class Date:\n", " day = 0\n", " month = 0\n", " year = 0\n", " \n", "class Family:\n", " dob = Date()\n", " name = \"\"\n", " pa_name = \"\"\n", " ma_name = \"\"\n", "\n", "members = []\n", "\n", "def get_person():\n", " while(True):\n", " temp = Family()\n", " print \"Enter the name of the person: \",\n", " temp.name = raw_input()\n", " print \"Enter %s's date of birth (day month year): \" %temp.name\n", " temp.dob.day = int(raw_input(\"Day: \"))\n", " temp.dob.month = int(raw_input(\"Month: \"))\n", " temp.dob.year = int(raw_input(\"Year: \"))\n", " print \"Who is %s's father? \" %temp.name,\n", " temp.pa_name = raw_input()\n", " print \"Who is %s's mother? \" %temp.name,\n", " temp.ma_name = raw_input()\n", " print \"\\nDo you want to enter details of a person (Y or N)? \",\n", " more = raw_input()\n", " members.append(temp)\n", " if(more.lower() == 'n'):\n", " return\n", "\n", "def show_person_data():\n", " fp = open(\"myfile.bin\", \"rb\")\n", " count = 0\n", " while(True):\n", " line = fp.readline()\n", " if line:\n", " member_data = line.split(\",\")\n", " print \"%s's father is %s, and mother is %s.\" %(member_data[0],member_data[4], member_data[5])\n", " found_relative, relative_info = get_parent_dob(members[count])\n", " if found_relative:\n", " print relative_info\n", " else:\n", " print \"No info on parents available\"\n", " else:\n", " break\n", " fp.close()\n", "\n", "def get_parent_dob(member):\n", " parent_info = \"\"\n", " found_relative = False\n", " for parent in members:\n", " if parent.name == member.pa_name:\n", " parent_info = parent_info+\"Pa was born on %d %d %d\" %(parent.dob.day, parent.dob.month, parent.dob.year)\n", " found_relative = True\n", " elif parent.name == member.ma_name:\n", " parent_info = parent_info+\" Ma was born on %d %d %d\" %(parent.dob.day, parent.dob.month, parent.dob.year)\n", " found_relative = True\n", " return found_relative, parent_info\n", "\n", "\n", "print \"Do you want to add details of a person ? (Y/N): \",\n", "more = raw_input()\n", "if more.lower() == 'n':\n", " import sys\n", " sys.exit()\n", "\n", "get_person()\n", "fp = open(\"myfile.bin\", \"wb\")\n", "for member in members:\n", " line = member.name+\",\"+str(member.dob.day)+\",\"+str(member.dob.month)+\",\"+str(member.dob.year) +\",\"+member.pa_name+\",\"+member.ma_name\n", " fp.write(line)\n", " fp.write(\",\\n\")\n", "fp.close()\n", "show_person_data()" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 11 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Program 12.6, page no. 531" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Program 12.6, page no. 531\n", "\n", "\"\"\"\n", "Writing a binary file with an update mode\n", "\"\"\"\n", "\n", "MAXLEN = 50\n", "\n", "def listfile():\n", " fp = open(\"mypeople.bin\", \"rb\")\n", " print \"The folks recorded in the mypeople.bin file are: \"\n", " while(True):\n", " line = fp.readline()\n", " if line:\n", " print line.split(\",\")[0], \"\\t\\t\\t\\t\\t\", line.split(\",\")[1]\n", " else:\n", " break\n", " fp.close()\n", "\n", "answer = 'y'\n", "fp = open(\"mypeople.bin\", \"wb\")\n", "while(answer.lower() == 'y'):\n", " print \"Enter a name less than %d characters: \" %MAXLEN,\n", " name = raw_input()\n", " print \"Enter the age of %s: \" %name,\n", " age = int(raw_input())\n", " length = len(name)\n", " line = name+\",\"+str(age)\n", " fp.write(line)\n", " fp.write(\" \\n\")\n", " print \"Do you want to enter another(y or n)? \",\n", " answer = raw_input()\n", "fp.close()\n", "listfile()" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 11 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Program 12.7, page no. 545" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Program 12.7, page no. 545\n", "\n", "\"\"\"\n", "Writing, reading and updating a binary file\n", "\"\"\"\n", "\n", "class Record:\n", " name = \"\"\n", " age = 0\n", "\n", "records = []\n", "\n", "def write_file(mode):\n", " global filename\n", " fp = open(filename, mode)\n", " more = 'y'\n", " while(more == 'y'):\n", " print \"Enter name less than 30 characters: \",\n", " name = raw_input()\n", " name = \"%30s\" %name\n", " print \"Enter age of \", name\n", " age = raw_input()\n", " age = \"%3s\" %age\n", " line = name+\",\"+age\n", " fp.write(line)\n", " fp.write(\" \\n\")\n", " print \"Do you want to enter another (y/n)? \",\n", " more = raw_input()\n", " fp.close()\n", " return\n", "\n", "def list_file():\n", " global filename\n", " fp = open(filename, \"rb\")\n", " print \"The folks recorded in the mypeople.bin file are: \"\n", " while(True):\n", " line = fp.readline()\n", " if line:\n", " line_split = line.split(\",\")\n", " print line_split[0].strip(), \"\\t\\t\\t\\t\\t\", line_split[1]\n", " else:\n", " break\n", " fp.close()\n", "\n", "def remove(fname):\n", " import os\n", " os.remove(fname)\n", "\n", "def update_file():\n", " global filename\n", " new_record = Record()\n", " fp = open(filename, \"rb+\")\n", " print \"Enter name to be updated: \",\n", " update_name = raw_input()\n", " update_name = \"%30s\"%update_name\n", " while(True):\n", " old_pos = fp.tell()\n", " old_line = fp.readline()\n", " if old_line:\n", " if old_line.split(\",\")[0] == update_name:\n", " print \"You can now enter new name and age for \", update_name\n", " print \"Enter name less than 30 charactesrs: \",\n", " new_name = raw_input()\n", " new_name = \"%30s\"%new_name\n", " print \"Enter age for \", new_name\n", " new_age = raw_input()\n", " new_age = \"%3s\"%new_age\n", " pos = fp.tell()\n", " fp.seek(old_pos)\n", " new_line = new_name+\",\"+new_age+\" \\n\"\n", " new_line = old_line.replace(old_line, new_line)\n", " fp.write(new_line)\n", " else:\n", " break\n", " fp.close()\n", " \n", "filename = \"my-people.bin\"\n", "answer = 'q'\n", "while(True):\n", " print \"Choose from the following options: \"\n", " print \"To list the file contents enter L\"\n", " print \"To create a new file enter C \"\n", " print \"To add new records enter A\"\n", " print \"To update existing records enter U\"\n", " print \"To delete the file enter D\"\n", " print \"To end the program enter Q: \",\n", " answer = raw_input()\n", " if answer.upper() == 'L':\n", " list_file()\n", " elif answer.upper() == 'C':\n", " write_file(\"wb+\")\n", " print \"File creation complete.\"\n", " elif answer.upper() == 'A':\n", " write_file(\"ab+\");\n", " print \"File append complete.\"\n", " elif answer.upper() == 'U':\n", " update_file()\n", " elif answer.upper() == 'D':\n", " print \"Are you sure you want to delete %s (y or n)? \",\n", " confirm_delete = raw_input()\n", " if(confirm_delete.lower() == 'y'):\n", " remove(filename)\n", " elif answer.upper() == 'Q':\n", " print \"Ending the program. \"\n", " import sys\n", " sys.exit()\n", " else:\n", " print \"Invalid selection. Try again.\"" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 11 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Program 12.8, page no. 551" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import binascii\n", "\n", "print \"Enter filename: \",\n", "filename = raw_input()\n", "\n", "f = open(filename, \"r\")\n", "\n", "for line in f.readlines():\n", " print (binascii.hexlify(line)),\n", " print \" | \", line\n", "\n", "f.close()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Enter filename: " ] }, { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "myfile.txt\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ " 2e68746f726220656874206c696f707320736b6f6f6320796e616d206f6f54 | .htorb eht liops skooc ynam ooT\n" ] } ], "prompt_number": 14 } ], "metadata": {} } ] }