Chapter 5 : Reading and writing files

Example 5.1, Page No 81

In [6]:
poem  = ["\n\tI never saw a man who looked"]
poem.append("\n\tWith such a wistful eye")
poem.append("\n\tUpon that little tent of blue")
poem.append("\n\tWhich prisoners call the sky")
try:
    writer = open("poem.txt","w")
    if(not isinstance(writer,file)):
        print "Error opening file for output"
    writer.writelines(poem)
    writer.close()
except IOError:
    print "Error opening file for output"
"""
Out put Text File :- poem.txt

    I never saw a man who looked
    With such a wistful eye
    Upon that little tent of blue
    Which prisoners call the sky
    The Ballad of Reading Gaol
            Oscar Wilde 1898
            
"""

Example 5.2, Page No 83

In [6]:
info = "\n\tThe Ballad of Reading Gaol"
info = info + "\n\t\t\tOscar Wilde 1898" #There is no append for string in python
try:
    writer = open("poem.txt","a")
    if(not isinstance(writer,file)):
        print "Error opening file for output"
    writer.writelines(info)
    writer.close()
except IOError:
    print "Error opening file for output"

Example 5.3, Page No 84

In [7]:
try:
    reader = open("poem.txt","r")
    if(not isinstance(reader,file)):
        print "Error opening input file"
    i = 0
    while(1):
        c = reader.read(1)
        if c == "":
            break
        else:
            print c,
            i= i + 1    
    reader.close()
    print "\nIterations: ",i
except IOError:
    print "Error opening input file"
	I   n e v e r   s a w   a   m a n   w h o   l o o k e d 
	W i t h   s u c h   a   w i s t f u l   e y e 
	U p o n   t h a t   l i t t l e   t e n t   o f   b l u e 
	W h i c h   p r i s o n e r s   c a l l   t h e   s k y 
	T h e   B a l l a d   o f   R e a d i n g   G a o l 
			O s c a r   W i l d e   1 8 9 8 
Iterations:  164

Example 5.4, Page No 86

In [24]:
# this program gives output same as book program but logic is different because some of functions are not available in python
RANGE = 12
tab = range(RANGE)
i = 0
j = 1
t = ""
try:
    reader = open("records.txt","r")
    if(not isinstance(reader,file)):
        print "Error opening input file"
    while(1):
        c = reader.read(1)
        if c == "":
            break
        else:
            t = t + c
            if c == '\t':
                tab[i] = t
                t = ""
                i = i + 1
            elif c == '\n':
                tab[i] = t
                t = ""
                i = i + 1
            elif i == RANGE-1:
                tab[i] = t
    reader.close()
    i= 0;
    while i < RANGE:
        print "Record Number: ",j
        j = j + 1
        print "Forename: ",tab[i]
        i = i + 1
        print "Surname: ",tab[i]
        i = i + 1
        print "Department: ",tab[i]
        i = i + 1
        print "Telephone: ",tab[i]
        i = i + 1
except IOError:
    print "Error opening input file"

"""
    INPUT FILE :- records.txt
    
    John   Smith   Sales   555-1234
    Mary   Jones   Wages   555-9876
    Paul   Harris  Accts   555-4321
    
"""
Record Number:  1
Forename:  John	
Surname:  Smith	
Department:  Sales	
Telephone:  555-1234

Record Number:  2
Forename:  Mary	
Surname:  Jones	
Department:  Wages	
Telephone:  555-9876

Record Number:  3
Forename:  Paul	
Surname:  Harris	
Department:  Accts	
Telephone:  555-4321

Example 5.5, Page No 89

In [16]:
isTrue = 1
num = 255
for i in range(0,40):
    print ".",
print  "Output"
print "Pi: ","3.1415926536"
print isTrue,":",bool(isTrue)
print num,":","{:01X}".format(num)
 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Output
Pi:  3.1415926536
1 : True
255 : FF

Example 5.6, Page No 91

In [20]:
try:
    for number in range(1,21):
        if number > 4:
            raise Exception(number)
        else:
            print "Number: ",number
except:
    print "Exception at: ",number
Number:  1
Number:  2
Number:  3
Number:  4
Exception at:  5

Example 5.7, Page No 92

In [23]:
import sys
lang = "C++"
try:
    lang.erase(4,6)
except:
    print "Exception",sys.exc_info()[0]
# There is  no support for erse method in python
Exception <type 'exceptions.AttributeError'>

Example 5.8, Page No 94

In [29]:
#there is no replace or resize method in python
import sys
lang = "C++"
num = 1000000000
try:
    lang.replace(lang,"C","1")
    lang.resize(3*num)
    reader = open("nonsuch.txt","r")
    print "Program continues..."
except:
    print sys.exc_info()[0]
    print "Program terminated."
#python dose not support much more exceptions
<type 'exceptions.TypeError'>
Program terminated.