Chapter 11 : File Input and Output

Example 11.1, Page No 250

In [3]:
try:
    pRead = open("file1.dat","r")
except IOError:
    print "\nFile can not be opened\n"

"""
Input file:- file1.dat
"""

Example 11.2, Page No 252

In [2]:
try:
    pRead = open("file1.dat","r")
    if(not isinstance(pRead,file)):
        print "\nFile can not be opened\n"
    else:
        print "\nFile opened for reading\n"
    pRead.close()
except IOError:
    print "\nFile can not be opened\n"

"""
Input file:- file1.dat
"""
File opened for reading

Example 11.3, Page No 253

In [3]:
try:
    pRead = open("names.dat","r")
    if(not isinstance(pRead,file)):
        print "\nFile can not be opened\n"
    else:
        print "\nContents of names.dat\n"
        while(1):
            t = pRead.readline() 
            if(t != ""):
                print t
            else:
                break
    pRead.close()
except IOError:
    print "\nFile can not be opened\n"
    
""" 
Input File :- names.dat

Michael
Sheila
Spencer
Olivia

"""
Contents of names.dat

Michael

Sheila

Spencer

Olivia

Example 11.4, Page No 255

In [5]:
try:
    pRead = open("hobbies.dat","r")
    if(not isinstance(pRead,file)):
        print "\nFile can not be opened\n"
    else:
        print "\nName\tHobby\n\n"
        while(1):
            name = pRead.readline()
            hobby = pRead.readline()
            if(name != ""):
                print name + "\t"
                print hobby
            else:
                break
    pRead.close()
except IOError:
    print "\nFile can not be opened\n"
    
"""
Input file :- hobbies.dat

Michael	Programming
Sheila	Shopping
Spencer	Football
Olivia	Dancing
Waytt	Eating
"""
Name	Hobby


Michael	Programming
	
Sheila	Shopping

Spencer	Football
	
Olivia	Dancing

Example 11.5, Page No 256

In [7]:
try:
    pWrite = open("students.dat","w")
    if(not isinstance(pWrite,file)):
        print "\nFile can not be opened\n"
    else:
        fname = raw_input("Enter first name: ")
        lname = raw_input("Enter last name: ")
        id1 = raw_input("Enter id: ")
        gpa = float(raw_input("Enter GPA: "))
        pWrite.writelines(fname + " " + lname + "\t" + id1 + "\t" + str(gpa))
    pWrite.close()
except IOError:
    print "\nFile can not be opened\n"

"""
Output file:- students.dat
Patric Star	888-66-9999	2.0
"""
Enter first name: Patric
Enter last name: Star
Enter id: 888-66-9999
Enter GPA: 2.00

Example 11.6, Page No 258

In [8]:
try:
    pRead = open("students.dat","r")
    if(not isinstance(pRead,file)):
        print "\nFile can not be opened\n"
    else:
        print "\nName\t\tID\t\tGPA\n\n"
        while(1):
            fname = pRead.read()
            lname = pRead.read()
            id1 = pRead.read()
            gpa = pRead.read()
            
            if(fname != ""):
                print fname + lname + "\t\t" + id1 + "\t" + str(gpa)
            else:
                break
    pRead.close()
except IOError:
    print "\nFile can not be opened\n"

"""
Input file:- students.dat
Patric Star	888-66-9999	2.0
"""
Name		ID		GPA


Patric Star	888-66-9999	2.0			

Example 11.7, Page No 259

In [16]:
def readData():
    try:
        pRead = open("hobbies.dat","r")
        if(not isinstance(pRead,file)):
            print "\nFile can not be opened\n"
        else:
            print "\nName\tHobby\n\n"
            while(1):
                name = pRead.readline()
                hobby = pRead.readline()
                if(name != ""):
                    print name + "\t"
                    print hobby
                else:
                    break
        pRead.close()
    except IOError:
        print "\nFile can not be opened\n"
try:
    print "Current file contains"
    readData()
    print "\n"
    name = raw_input("Enter a new name: ")
    hobby = raw_input("Enter a new hobby: ")
    pWrite = open("hobbies.dat","a")
    if(not isinstance(pWrite,file)):
        print "\nFile can not be opened\n"
    else:
        pWrite.writelines("\n" + name + "\t" + hobby)
    pWrite.close()
    readData()
except IOError:
    print "\nFile can not be opened\n"
    
"""
Input file and Output file:- hobbies.dat
Michael	Programming
Sheila	Shopping
Spencer	Football
Olivia	Dancing
Waytt	Eating
"""
Current file contains

Name	Hobby


Michael	Programming
	
Sheila	Shopping

Spencer	Football
	
Olivia	Dancing


Enter a new name: Waytt
Enter a new hobby: Eating

Name	Hobby


Michael	Programming
	
Sheila	Shopping

Spencer	Football
	
Olivia	Dancing

Waytt	Eating	

Example 11.8, Page No 263

In [20]:
import sys
try:
    pRead = open("hobbies.dat","r")
    if(not isinstance(pRead,file)):
        print "\nFile can not be opened\n"
        print "The following error occurred" #goto label
        sys.exit("Some Error Occures")
    else:
        print "\nName\tHobby\n\n"
        while(1):
            name = pRead.readline()
            hobby = pRead.readline()
            if(name != ""):
                print name + "\t"
                print hobby
            else:
                break
    pRead.close()
    #sys.exit("Exit")
except IOError:
    print "\nFile can not be opened\n"

"""
Input file:- hobbies.dat
Michael	Programming
Sheila	Shopping
Spencer	Football
Olivia	Dancing
Waytt	Eating
"""
Name	Hobby


Michael	Programming
	
Sheila	Shopping

Spencer	Football
	
Olivia	Dancing

Waytt	Eating	

Example 11.9, Page No 266

In [1]:
print "\n\tPhone Book\n"
print "\n 1 \t Add phone book entry \n"
print "2 \t Print phone book \n\n"
print "Select an option: "
response = int(raw_input("Select an option: "))
print response
if(response == 1):
    fname = raw_input("Enter first name: ")
    lname = raw_input("Enter last name: ")
    number = raw_input("Enter phone number: ")
    pWrite = open("phone_book.dat","a")
    if(isinstance(pWrite,file)):
       pWrite.writelines(fname + " " + lname + " " + number + "\n")
       pWrite.close()
    else:
        print "The error occured" #go to
elif(response == 2):
    pRead = open("phone_book.dat","r")
    if(isinstance(pRead,file)):
        while(1):
            fname = pRead.read()
            if(fname == ""):
                break
            lname = pRead.read()
            number = pRead.read()
            print fname
            print lname
            print number
        print "\n"
    else:
        print "The error occured" #go to
else:
    print "Invalid Selection"

"""
Input file and Output file:- phone_book.dat
John Smith 538.676.1234
"""
	Phone Book


 1 	 Add phone book entry 

2 	 Print phone book 


Select an option: 
Select an option: 2
2
John Smith 538.676.1234