Chapter 7: Structures and File Input/Output

C28ST1 :Page 592

In [1]:
from collections import namedtuple
#Structure declaration and definition
struct_cd_collection = namedtuple("struct_cd_collection", "title artist num_songs price date_purch")
#Structure for Cd Collection
cd1 = struct_cd_collection("Red Moon Men", "Sam and the Sneeds", 12,11.95,"02/13/92")

#Result
print "Here is the CD information :\n\n"
print "Title:",cd1.title,"\n"
print "Artist:",cd1.artist,"\n"
print "Songs:",cd1.num_songs,"\n"
print "Price:",cd1.price,"\n"
print "Date purchased:",cd1.date_purch,"\n"
Here is the CD information :


Title: Red Moon Men 

Artist: Sam and the Sneeds 

Songs: 12 

Price: 11.95 

Date purchased: 02/13/92 

C28ST2 :Page 593

In [3]:
from collections import namedtuple

#Structure initial declaration
students = namedtuple("students", "name age average")
#Get data
print "What is first student's name? ",
x=raw_input()
print "What is the first student's age? ",
y=input()
print "What is the first student's average ? ",
z=input()
#Assign data to the structure variable
student1=students(x,y,z)
print "\n"
#Get data
print "What is second student's name? ",
x=raw_input()
print "What is the second student's age? ",
y=input()
print "What is the second student's average ? ",
z=input()
#Assign data to the structure variable
student2=students(x,y,z)
#Result
print "\n\nHere is the student information you entered:\n\n"
print "Student #1:\n"
print "Name:    ",student1.name,"\n"
print "Age:     ",student1.age,"\n"
print "Average: ",'%.2f'%student1.average,"\n"
print "Student #2:\n"
print "Name:    ",student2.name,"\n"
print "Age:     ",student2.age,"\n"
print "Average: ",'%.2f'%student2.average,"\n"
What is first student's name? Larry
 What is the first student's age? 14
 What is the first student's average ? 87.67
 

What is second student's name? Judy
 What is the second student's age? 15
 What is the second student's average ? 95.38
 

Here is the student information you entered:


Student #1:

Name:     Larry 

Age:      14 

Average:  87.67 

Student #2:

Name:     Judy 

Age:      15 

Average:  95.38 

C28ST3 :Page 596

In [4]:
#Function definitions
def fill_structs(student_var):
    #Get student data
    print "What is student's name? ",
    x=raw_input()
    print "What is the student's age? ",
    y=input()
    print "What is the student's average ? ",
    z=input()
    student_var=students(x,y,z)
    return student_var
def pr_students(student_var):
    print "Name:    ",student_var.name,"\n",
    print "Age:     ",student_var.age,"\n",
    print "Average: ",student_var.average,"\n",
#Structure declaration
from collections import namedtuple
students=namedtuple("students","name age average")
#Structure variable declaration
student1=students(" ",0,0.0)
student2=students(" ",0,0.0)
#Stucture variable is passed as copy to the function
student1=fill_structs(student1)
student2=fill_structs(student2)
#Result
print "\n\nHere is the student information you entered:\n\n"
pr_students(student1)
pr_students(student2)
What is student's name? Larry
 What is the student's age? 14
 What is the student's average ? 87.67
 What is student's name? Judy
 What is the student's age? 15
 What is the student's average ? 97.38
 

Here is the student information you entered:


Name:     Larry 
Age:      14 
Average:  87.67 
Name:     Judy 
Age:      15 
Average:  97.38 

C28CUST :Page 598

In [5]:
#Structure definition
from collections import namedtuple
customer_rec=namedtuple("customer_rec","cust_name balance dist_rate")
customer=customer_rec("Steve Thompson",431.23,.25)
print "Before the update",customer.cust_name," has a balance of $",'%.2f' %customer.balance,"\n",
#Update the balance
customer_rec.balance=customer.balance*(1.0-customer.dist_rate)
#Result
print "After the update",customer.cust_name," has a balance of $",'%.2f' %customer.balance,"\n",
Before the update Steve Thompson  has a balance of $ 431.23 
After the update Steve Thompson  has a balance of $ 323.42 

C28STCPY :Page 599

In [6]:
#Structure declaration
from collections import namedtuple
students=namedtuple("students","st_name grade age average")
#Structure variable declaration
std1=students("Joe Brown",'A',13,91.4)
std2=students(" "," ",0,0.0)
std3=students(" "," ",0,0.0)
#Assigning one structure variable to another.
std2=std1
std3=std1
#Result
print "The contents of std2:\n",
print std2.st_name,", ",std2.grade,", ",std2.age,", ",'%.1f' %std2.average,"\n\n"
print "The contents of std3:\n",
print std3.st_name,", ",std3.grade,", ",std3.age,", ",'%.1f' %std3.average,"\n\n"
The contents of std2:
Joe Brown ,  A ,  13 ,  91.4 


The contents of std3:
Joe Brown ,  A ,  13 ,  91.4 


C30WR1 :Page 635

In [1]:
#open a new file in write mode
fp = open ("NAMES.txt", "w" ) 
fp.writelines("Michel Langston\n")
fp.writelines("Sally Redding\n")
fp.writelines("Jane Kirk\n")
fp.writelines("Stacy Wikert\n")
fp.writelines("Joe Hiquet\n")
#Close file
fp.close()
#Result
print "names were written into the file"
names were written into the file

C30WR2 :Page 636

In [2]:
#Creates a file in write mode
fp = open ( "NUMS.1.txt", "w" )      
if not fp:
    print "Error opening file.\n"
else:
    for ctr in range(1,101,1):
        fp.write('%d' %ctr)                     #Writes number from 1-100 into the file
fp.close()
#Result
print "ctr value is written into the file"
ctr value is written into the file

C30AP1 :Page 638

In [3]:
#opens existing file
fp = open ( "NAMES.txt", "a" ) 
#Adds to file
fp.writelines("Johnny Smith\n")
fp.writelines("Laura Hull \n")
fp.writelines("Mark Brown\n")
#Close file
fp.close()
#Result
print "Names are added to the existing file"
Names are added to the existing file

C30RE2 :Page 641

In [1]:
#File1 to take backup
print "What is the name of the file you want to back up? "
in_filename=raw_input()
#File2 to copy contents
print "What is the name of the file you want to copy ",in_filename,"to? "
out_filename=raw_input()
in_fp=open(in_filename,"r")
if not in_fp:
    print "\n\n*** ",in_filename,"does not exist***\n"
    exit(0)
else:
    out_fp=open(out_filename,"w")
    if not out_fp:
        print "\n\n*** Error opening ",out_filename,"***\n"
        exit(0)
    else:
        print "\nCopying...\n"                          #Reads from old file 
        for in_char in in_fp.readlines():               #and copies it to new file
            out_fp.writelines(in_char)
        print "\nThe file is copied.\n"
#Close all files
in_fp.close()
out_fp.close()
What is the name of the file you want to back up? 
NAMES.txt
What is the name of the file you want to copy  NAMES.txt to? 
NEW_NAMES.txt

Copying...


The file is copied.

C32CON :Page 664

In [1]:
PI = 3.14159
class Sphere:                                                           #Class declaration
    def __init__(self, xcoord,ycoord,zcoord,radius):
        self.r = radius
        self.x = xcoord
        self.y = ycoord
        self.z = zcoord
        
    def volume(self):
        return r*r*r*4*PI/3

    def surface_area(self):
        return r*r*4*PI
def main():
    s = Sphere(1.0,2.0,3.0,4.0)                                      #Class object    
    print "X=",s.x,", Y=",s.y,", Z=",s.z,", R=",s.r         #Result

main()
X= 1.0 , Y= 2.0 , Z= 3.0 , R= 4.0

C32DES :Page 665

In [2]:
PI = 3.14159
#Class declaration
class Sphere:                                                          
    def __init__( self,xcoord,ycoord,zcoord,radius):
        self.r = radius
        self.x = xcoord
        self.y = ycoord
        self.z = zcoord
    def __del__(self):
        print "Sphere(",self.x,"," ,self.y,",",self.z,",",self.r,") destroyed"
    def volume(self):
        return self.r*self.r*self.r*4*PI/3
    def surface_area(self):
        return self.r*self.r*4*PI
def main():
    #Class object
    s = Sphere(1.0,2.0,3.0,4.0)                                      
    #Result
    print "X=",s.x,", Y=",s.y,", Z=",s.z,", R=",s.r         
main()
X= 1.0 , Y= 2.0 , Z= 3.0 , R= 4.0
Sphere( 1.0 , 2.0 , 3.0 , 4.0 ) destroyed

C32MEM :Page 667

In [3]:
PI = 3.14159
#Class declaration
class Sphere:                                                           
    def __init__( self,xcoord,ycoord,zcoord,radius):
        self.r = radius
        self.x = xcoord
        self.y = ycoord
        self.z = zcoord
    def __del__(self):
        print "Sphere(",self.x,"," ,self.y,",",self.z,",",self.r,") destroyed"
    def volume(self):
        return self.r*self.r*self.r*4*PI/3
    def surface_area(self):
        return self.r*self.r*4*PI
def main():
    #Class object
    s = Sphere(1.0,2.0,3.0,4.0)                                      
    #Result
    print "X=",s.x,", Y=",s.y,", Z=",s.z,", R=",s.r         
    print "The volume is ",s.volume(),"\n",
    print "The surface area is ",s.surface_area(),"\n",
main()
X= 1.0 , Y= 2.0 , Z= 3.0 , R= 4.0
The volume is  268.082346667 
The surface area is  201.06176 
Sphere( 1.0 , 2.0 , 3.0 , 4.0 ) destroyed

C32MEM1 :Page 668

In [4]:
PI = 3.14159
#Class declaration
class Sphere:                                                           
    def __init__( self,xcoord,ycoord,zcoord,radius):
        self.r = radius
        self.x = xcoord
        self.y = ycoord
        self.z = zcoord
    def __del__(self):
        print "Sphere(",self.x,"," ,self.y,",",self.z,",",self.r,") destroyed"
    def volume(self):
        return self.r*self.r*self.r*4*PI/3
    def surface_area(self):
        return self.r*self.r*4*PI
def main():
    #Class object
    s = Sphere(1.0,2.0,3.0,4.0)                                      
    #Result
    print "X=",s.x,", Y=",s.y,", Z=",s.z,", R=",s.r         
    print "The volume is ",s.volume(),"\n",       
    print "The surface area is ",s.surface_area(),"\n",
main()
X= 1.0 , Y= 2.0 , Z= 3.0 , R= 4.0
The volume is  268.082346667 
The surface area is  201.06176 
Sphere( 1.0 , 2.0 , 3.0 , 4.0 ) destroyed

C32MEM1A :Page 669

In [5]:
PI = 3.14159
#Class declaration
class Sphere:                                                           
    def __init__( self,xcoord,ycoord,zcoord,radius):
        self.r = radius
        self.x = xcoord
        self.y = ycoord
        self.z = zcoord
    def __del__(self):
        print "Sphere(",self.x,"," ,self.y,",",self.z,",",self.r,") destroyed"
    def volume(self):
        return self.r*self.r*self.r*4*PI/3
    def surface_area(self):
        return self.r*self.r*4*PI
def main():
    #Class object
    s = Sphere(1.0,2.0,3.0,4.0)                                      
    #Result
    print "X=",s.x,", Y=",s.y,", Z=",s.z,", R=",s.r         
    print "The volume is ",(s.r*s.r*s.r*4*PI/3),"\n",       #volume() function is expanded here
    print "The surface area is ",s.surface_area(),"\n",
main()
X= 1.0 , Y= 2.0 , Z= 3.0 , R= 4.0
The volume is  268.082346667 
The surface area is  201.06176 
Sphere( 1.0 , 2.0 , 3.0 , 4.0 ) destroyed

C32DEF :Page 671

In [6]:
PI = 3.14159
#Class declaration
class Sphere:                                                           
    def __init__( self,xcoord,ycoord=2.0,zcoord=2.5,radius=1.0):
        self.r = radius
        self.x = xcoord
        self.y = ycoord
        self.z = zcoord
    def __del__(self):
        print "Sphere(",self.x,"," ,self.y,",",self.z,",",self.r,") destroyed"
    def volume(self):
        return self.r*self.r*self.r*4*PI/3
    def surface_area(self):
        return self.r*self.r*4*PI
def main():
    #Class objects
    s = Sphere(1.0)                                     
    t = Sphere(1.0,1.1)
    u = Sphere(1.0,1.1,1.2)
    v = Sphere(1.0,1.1,1.2,1.3)
    #Result
    print "s: X=",s.x,", Y=",s.y,", Z=",s.z,", R=",s.r         
    print "The volume is ",s.volume(),"\n",       
    print "The surface area is ",s.surface_area(),"\n",
    print "t: X=",t.x,", Y=",t.y,", Z=",t.z,", R=",t.r        
    print "The volume is ",t.volume(),"\n",      
    print "The surface area is ",t.surface_area(),"\n",
    print "u: X=",u.x,", Y=",u.y,", Z=",u.z,", R=",u.r         
    print "The volume is ",u.volume(),"\n",       
    print "The surface area is ",u.surface_area(),"\n",
    print "v: X=",v.x,", Y=",v.y,", Z=",v.z,", R=",v.r        
    print "The volume is ",v.volume(),"\n",       
    print "The surface area is ",v.surface_area(),"\n",
main()
s: X= 1.0 , Y= 2.0 , Z= 2.5 , R= 1.0
The volume is  4.18878666667 
The surface area is  12.56636 
t: X= 1.0 , Y= 1.1 , Z= 2.5 , R= 1.0
The volume is  4.18878666667 
The surface area is  12.56636 
u: X= 1.0 , Y= 1.1 , Z= 1.2 , R= 1.0
The volume is  4.18878666667 
The surface area is  12.56636 
v: X= 1.0 , Y= 1.1 , Z= 1.2 , R= 1.3
The volume is  9.20276430667 
The surface area is  21.2371484 
Sphere( 1.0 , 2.0 , 2.5 , 1.0 ) destroyed
Sphere( 1.0 , 1.1 , 2.5 , 1.0 ) destroyed
Sphere( 1.0 , 1.1 , 1.2 , 1.0 ) destroyed
Sphere( 1.0 , 1.1 , 1.2 , 1.3 ) destroyed

C32OVCON :Page 673

In [7]:
PI = 3.14159
#Class declaration
class Sphere:                                                               
    def __init__( self,xcoord,ycoord,zcoord,radius):
        self.r = radius
        self.x = xcoord
        self.y = ycoord
        self.z = zcoord
    def __del__(self):
        print "Sphere(",self.x,"," ,self.y,",",self.z,",",self.r,") destroyed"
    def volume(self):
        return self.r*self.r*self.r*4*PI/3
    def surface_area(self):
        return self.r*self.r*4*PI
def main():
    #Class object
    s = Sphere(1.0,2.0,3.0,4.0)                                      
    #Result
    print "X=",s.x,", Y=",s.y,", Z=",s.z,", R=",s.r         
    print "The volume is ",(s.r*s.r*s.r*4*PI/3),"\n",       #volume() function is expanded here
    print "The surface area is ",s.surface_area(),"\n",
main()
X= 1.0 , Y= 2.0 , Z= 3.0 , R= 4.0
The volume is  268.082346667 
The surface area is  201.06176 
Sphere( 1.0 , 2.0 , 3.0 , 4.0 ) destroyed