# Chapter 12: Streams and Files¶

## Example 12.1, Page Number 581¶

In [1]:
def isFeet(str):             #return true if the string is a correct feet value

slen = len(str)          #get length

if slen==0 or slen>5:    #if no input, or too long
return False         #not an int

for j in range(slen):    #check each character

if (str[j] < '0' or str[j] > '9' ) and str[j] != '-':       #if not digit or minus
return False     #string is not correct feet

n = float(str)           #convert to float

if(n<-999.0 or n>999.0):     #is it out of range
return False             #if so, not correct feet

return True             #it is correct feet

class Distance:                      #Distance class

def __init__(self,ft=0,inc=0):   #constructor
self.__feet = ft
self.__inches = inc

def showdist(self):              #display distance
print self.__feet , '\' -' , self.__inches , '\"'

def getdist(self):               #get length from user

while True:
self.__feet = raw_input('Enter feet:')       #it will not skip white space

if(isFeet(self.__feet)):              #is it a correct feet value?

self.__feet.replace(' ','')       #eat white spaces
self.__feet = int(self.__feet)    #convert to integer
break;                            #break out of 'while'

print 'Feet must be an integer less than 1000'

while True:                 #cycle untill inches are right

self.__inches = input('Enter inches:')           #get inches and do not skip white space

if(self.__inches<12.0 and self.__inches>0.0):
break;

if(self.__inches>=12.0 or self.__inches<0.0):
print 'Inches must be between 0.0 and 11.99'
print 'Incorrect inches input'

d = Distance()        #make a distance object

while True:
d.getdist()       #get its value from user

print 'Distance =',;d.showdist()           #display it

ans = raw_input("Do another (y/n)? ")

if ans == 'n':       #cycle untill 'n'
break

Enter feet:1 2 3
Feet must be an integer less than 1000
Enter feet:9999
Feet must be an integer less than 1000
Enter feet:99
Enter inches:14
Inches must be between 0.0 and 11.99
Incorrect inches input
Enter inches:11
Distance = 99 ' - 11 "
Do another (y/n)? y
Enter feet:-98
Enter inches:12
Inches must be between 0.0 and 11.99
Incorrect inches input
Enter inches:-98
Inches must be between 0.0 and 11.99
Incorrect inches input
Enter inches:11
Distance = -98 ' - 11 "
Do another (y/n)? n


## Example 12.2, Page Number 584¶

In [2]:
ch = "x"
str1 = "Kafka"           #strings without white spaces
str2 = "Proust"

outfile=open("fdata.txt",'w')      #open a file

outfile.write(ch)         #insert (write) data
outfile.write("77")
outfile.write("6.02")
outfile.write(' ')        #needed space between numbers and string
outfile.write(str1)
outfile.write(' ')        #needed space between strings
outfile.write(str2)

print 'File written'
outfile.close()

File written


## Example 12.3, Page Number 585¶

In [3]:
infile = open("fdata.txt",'r')    #open the file for reading

print ch,"\n",j,"\n",d,"\n",str1,"\n",str2,"\n",        #display the data

x
77
6.02
Kafka
Proust


## Example 12.4, Page Number 586¶

In [4]:
outfile = open("TEST.TXT",'w')         #create a file for output

#send text to file
outfile.write("I fear thee, ancient Marner!\n")
outfile.write("I fear thy skinny hand\n")
outfile.write("And thou art long, and lank, and brown,\n")
outfile.write("As is the ribbed sea sand.\n")

outfile.close()         #close the file


## Example 12.5, Page Number 587¶

In [5]:
MAX = 80                   #size of buffer
buffer = []*MAX            #character buffer

infile = open("TEST.TXT",'r')        #open a file to read

while buffer:                        #untill buffer has some data in it or untill end-of-file
print buffer,                    #display buffer

infile.close()          #close file

I fear thee, ancient Marner!
I fear thy skinny hand
And thou art long, and lank, and brown,
As is the ribbed sea sand.


## Example 12.6, Page Number 588¶

In [6]:
str = "Time is a great teache, but unfortunately " + "it kills all its puplies.  Berlioz"

outfile = open("Test.txt","w")          #create file for output

for j in range(len(str)):         #for each character
ch = ""+str[j]
outfile.write(ch),

print "File written"
outfile.close()

File written


## Example 12.7, Page Number 588¶

In [7]:
infile = open("Test.txt","r")     #open file for read

while ch != '':           #read untill EOF
print ch,             #display it

T i m e   i s   a   g r e a t   t e a c h e ,   b u t   u n f o r t u n a t e l y   i t   k i l l s   a l l   i t s   p u p l i e s .     B e r l i o z


## Example 12.8, Page Number 589¶

In [8]:
infile = open("Test.txt","r")      #open file for read


Time is a great teache, but unfortunately it kills all its puplies.  Berlioz


## Example 12.9, Page Number 590¶

In [9]:
MAX = 100                                #size of buffer
buff = [j for j in range(MAX)]           #buffer for integers and fill buffer with data (0, 1, 2, ...)

os = open("edata.txt",'r+b')             #first make edata.txt file

s = ''
for j in range(MAX):
s += '%d' %buff[j]
os.write(s)                   #write to file

for j in range(MAX):          #erase buffer
buff[j] = 0

os.seek(0,0)

for j in range (10):

for j in range(10,MAX):

c=0
for j in range(MAX):            #check data
if int(buff[j])!=j:
print "Data is incorrect\n"
c=1
break

if c==0:
print "Data is correct"

Data is correct


## Example 12.10, Page Number 592¶

In [10]:
from pickle import dump

class person:                  #class person

def getData(self):         #get person's data
self.name = raw_input("Enter name: ")     #person's name
self.age = input("Enter age: ")           #person's age

pers = person()          #create a person
pers.getData()           #get data for person

outfile = open("PERSON.txt",'wb')       #open file for write obect to it

dump(pers, outfile)              #write object

outfile.close()

Enter name: Coleridge
Enter age: 62


## Example 12.11, Page Number 593¶

In [11]:
from pickle import load

class person:

def showData(self):             #display person's data
print "Name:",self.name     #person's name
print "Age:",self.age       #person's age

pers = person()         #create person variable

infile = open("PERSON.txt",'rb')     #open file in binary mode

pers.showData()                      #display person

Name: Coleridge
Age: 62


## Example 12.12, Page Number 594¶

In [12]:
from pickle import dump,load

class person:                #class of persons

def getData(self):       #get person's data
self._name = raw_input("Enter name: ")
self._age = input("Enter age: ")

def showData(self):      #display person's data
print "   Name:",self._name
print "   Age:",self._age

pers = person()                   #create person object
file = open("Group.txt",'r+b')    #open file
c=0                               #for total number of objects

while True:
print "\nEnter person's data: "
pers.getData()           #get one person's data
dump(pers, file)  #wriet to file
c += 1

ch = raw_input("Enter another person (y/n)? ")
if(ch == 'n'):
break

file.seek(0,0)

print ''
for j in range(c):
print 'person:'
pers.showData()              #display person

Enter person's data:
Enter name: Whitney
Enter age: 20
Enter another person (y/n)? y

Enter person's data:
Enter name: Rainier
Enter age: 21
Enter another person (y/n)? y

Enter person's data:
Enter name: McKinley
Enter age: 22
Enter another person (y/n)? n

person:
Name: Whitney
Age: 20
person:
Name: Rainier
Age: 21
person:
Name: McKinley
Age: 22


## Example 12.13, Page Number 599¶

In [13]:
from pickle import load

class person:          #class of person's

def getData(self):          #get person's data
self._name = raw_input("Enter name: ")
self._age = input("Enter age: ")

def showData(self):         #dislay person's data
print "   Name:",self._name
print "   Age:",self._age

pers = person()         #create person object
infile = open("Group.txt",'r+b')        #create input file and open it
c=3
print 'There are',c,'persons in file'   #print number of objects in file

n = input("Enter person number: ")

print ''
for j in range(3):
if j==n-1:
pers.showData()         #display the person

There are 3 persons in file
Enter person number: 2

Name: Rainier
Age: 21


## Example 12.14, Page Number 601¶

In [14]:
from pickle import dump,load

MAX = 1000
buff = []*1000

for j in range(MAX):        #fill buffer with data
buff.append(j)

try:
os = open("edata.txt",'r+b')         #open a file

except IOError:
print "could not open output file"

print 'Writing...'

try:
dump(buff, os)       #write buffer to it
except IOError:
print "could not write ot file"

os.close()             #must close it

for j in range(MAX):   #clear buffer
buff[j]=0

try:
is1 = open("edata.txt",'r+b')     #open the same file in read mode

except IOError:
print "could not open output file"

try:
buff = load(is1)           #read file data and put it into a buffer
except IOError:
print "could not read from file"

c=0
for j in range(MAX):            #check data
if int(buff[j])!=j:
print "Data is incorrect\n"
c=1
break

if c==0:
print "Data is correct"

Writing...
Data is correct


## Example 12.15, Page Number 603¶

In [15]:
class error:                   #class error#

def rdstate(self):         #show the error state
try:
file = open("GROUP1.txt",'r')
return 0

except IOError:
return 4

def good(self):            #check no error occur to open the file
try:
file = open("GROUP1.txt",'r')
return 1

except IOError:
return 0

def eof(self):            #check end-of-file
try:
file = open("GROUP1.txt",'r')
return 1

except IOError:
return 0

def fail(self):           #check any error has come?
try:
file = open("GROUP1.txt",'r')
return 0

except IOError:
return 4

def bad(self):            #file can't be open
try:
file = open("GROUP1.txt",'r')
return 0

except IOError:
return 4

try:
file = open("GROUP1.txt",'r')

except IOError:
print "can't open output file"

print 'file =',hex(id(file))

file = error()

print 'Error state =',file.rdstate()
print 'good() =',file.good()
print 'eof() =',file.eof()
print 'fail() =',file.fail()

can't open output file
file = 0x37cd270L
Error state = 4
good() = 0
eof() = 0
fail() = 4


## Example 12.16, Page Number 604¶

In [16]:
from pickle import dump,load

class person:            #class of persons

def getData(self):                                #get person's data
self._name = raw_input("Enter name: ")        #person's name
self._age = input("Enter age: ")              #person's age

def showData(self):          #display person's data
print "   Name:",self._name
print "   Age:",self._age

def diskIn(self,pn,c):       #read person number pn from file

infile = open("PERSFILE.txt",'r+b')  #open file

for j in range(c):

if j==pn:
return self;

def diskOut(self):           #write person to end of file

outfile = open("PERSFILE.txt",'ab')   #open file
dump(self, outfile)            #write to it
outfile.close()

def diskCount(self,c):        #return number of persons in file
return c

p = person()         #make an empty person
c=0
outfile = open("PERSFILE.txt",'wb')        #open file to delete its containt
outfile.close()

while True:                                #save person to disk
print "\nEnter person's data: "
p.getData()                            #get data
p.diskOut()                            #write to disk
c += 1

ch = raw_input("Enter another person (y/n)? ")
if(ch == 'n'):                         #untill user enters 'n'
break

c = p.diskCount(c)                         #how many persons are in file?

print 'There are',c,'persons in file'

print ''
for j in range(c):            #for each person
print 'person'
p = p.diskIn(j,c)         #read person from disk
p.showData()              #display person

Enter person's data:
Enter name: Stimson
Enter age: 45
Enter another person (y/n)? y

Enter person's data:
Enter name: Hull
Enter age: 58
Enter another person (y/n)? y

Enter person's data:
Enter name: Acheson
Enter age: 63
Enter another person (y/n)? y

Enter person's data:
Enter name: Dules
Enter age: 72
Enter another person (y/n)? n
There are 4 persons in file

person
Name: Stimson
Age: 45
person
Name: Hull
Age: 58
person
Name: Acheson
Age: 63
person
Name: Dules
Age: 72


## Example 12.17, Page Number 608¶

In [17]:
from sys import getsizeof

employee_type = ["tmanager","tscientist","tlaborer"]
(tmanager,tscientist,tlaborer) = (0,1,2)                 #Atteching the names with number

LEN = 32                                                 #maximum length of last names
MAXEM = 100                                              #maximum length of employees

class employee:               #employee class
__name = [None]*LEN       #employee name
__n = 0                   #current number of employee
__arrap = []              #array of ptrs to emps

def getdata(self):                                     #get data from user
self.__name = raw_input("   Enter last name: ")
self.__number = input("   Enter number: ")         #employee number

def putdata(self):                                     #display data
print '    Name:',self.__name
print '    Number:',self.__number

def get_type(self):                                    #return the type of object

if getsizeof(self)==getsizeof(manager()):
return tmanager
elif getsizeof(self)==getsizeof(scientisit()):
return tscientist
elif getsizeof(self)==getsizeof(laborer()):
return tlaborer
else:
return tmanager

ch = raw_input("Enter selection: ")

#create specific employee type
if ch=='m':
employee.__arrap.append(manager())

elif ch=='s':
employee.__arrap.append(scientist())

elif ch=='l':
employee.__arrap.append(laborer())

else:
print 'Unknown command'

employee.__arrap[employee.__n].getdata()        #get employee data from user
employee.__n += 1                               #increase the number of employee

def display(self):                    #display all employees

for j in range(employee.__n):
print j+1,                    #display number

#display type
if employee.__arrap[j].get_type()==tmanager:
print '. Type: Manager'

elif employee.__arrap[j].get_type()==tscientist:
print '. Type: scientist'

elif employee.__arrap[j].get_type()==tlaborer:
print '. Type: laborer'

else:
print '. Unknown type'

employee.__arrap[j].putdata()       #display employee data

def write(self):                            #write all current memory object to file
ouf = open("EMPLOY.txt",'w')
ouf.close()

print 'Writing',employee.__n,'employees.'

try:
ouf = open("EMPLOY.txt",'ab')       #open file in binary mode
except IOError:
print "could not open file"

for j in range(employee.__n):                  #for every employee objects

etype = employee.__arrap[j].get_type()     #get its type
dump(etype, ouf)                    #write type to file

#find its size
if etype == tmanager:
size = getsizeof(manager)
elif etype == tscientist:
size = getsizeof(scientist)
elif etype == tlaborer:
size = getsizeof(laborer)

try:
dump(employee.__arrap[j], ouf)       #write employee object to file
except IOError:
print "could not write to file"

ouf.close()        #close the file

try:
inf = open("EMPLOY.txt",'rb')           #open file into binary mode
except IOError:
print "could not open file"

employee.__n = 0             #no employee in memeory yet

for j in range(c):

try:
except IOError:
print "could not read type from file"

if j==c:
break

if etype == tmanager:                               #make new employee of correct type
employee.__arrap[employee.__n] = manager()
size = getsizeof(manager)
elif etype == tscientist:
employee.__arrap[employee.__n] = scientist()
size = getsizeof(scientist)
elif etype == tlaborer:
employee.__arrap[employee.__n] = laborer()
size = getsizeof(laborer)
else:
print 'Unknown type in file'

try:
except IOError:
print "could not read type from file"

employee.__n += 1           #count employee

class manager(employee):                                       #management class
__title = [None]*LEN                                       #'vice-president' etc.

def getdata(self):
employee.getdata(self)
self.__title = raw_input("   Enter Title: ")
self.__dues = input("   Enter golf club dues: ")       #golf club dues

def putdata(self):
employee.putdata(self)
print '    Title:',self.__title
print '    golf club dues:',self.__dues

class scientist(employee):                                     #scientist class

def getdata(self):
employee.getdata(self)
self.__pubs = raw_input("   Enter Number of pubs: ")   #number of publication

def putdata(self):
employee.putdata(self)
print '    Number of publications:',self.__pubs

class laborer(employee):             #labour class
pass

z = 0
while True:

print "\n'a' --to add data for an employee \n'd' --display data for all employees\n'w' --write all employee data to file"
print "'r' --read all employee data to file\n'x' --exit"
ch = raw_input("Enter selection: ")

if ch == 'a':                  #add an employee to list
z += 1

elif ch == 'd':                #display all employess
employee().display()

elif ch == 'w':                #write employee to file
employee().write()

elif ch == 'r':                #read all employee from file

elif ch == 'x':                #exit program
break;
else:
print 'Unknown command'


'a' --to add data for an employee
'd' --display data for all employees
'w' --write all employee data to file
'r' --read all employee data to file
'x' --exit
Enter selection: a
Enter selection: m
Enter last name: Johnson
Enter number: 1111
Enter Title: President
Enter golf club dues: 20000

'a' --to add data for an employee
'd' --display data for all employees
'w' --write all employee data to file
'r' --read all employee data to file
'x' --exit
Enter selection: a
Enter selection: s
Enter number: 2222
Enter Number of pubs: 99

'a' --to add data for an employee
'd' --display data for all employees
'w' --write all employee data to file
'r' --read all employee data to file
'x' --exit
Enter selection: a
Enter selection: l
Enter last name: Smith
Enter number: 3333

'a' --to add data for an employee
'd' --display data for all employees
'w' --write all employee data to file
'r' --read all employee data to file
'x' --exit
Enter selection: w
Writing 3 employees.

'a' --to add data for an employee
'd' --display data for all employees
'w' --write all employee data to file
'r' --read all employee data to file
'x' --exit
Enter selection: r

'a' --to add data for an employee
'd' --display data for all employees
'w' --write all employee data to file
'r' --read all employee data to file
'x' --exit
Enter selection: d
1 . Type: Manager
Name: Johnson
Number: 1111
Title: President
golf club dues: 20000
2 . Type: Manager
Number: 2222
Number of publications: 99
3 . Type: Manager
Name: Smith
Number: 3333

'a' --to add data for an employee
'd' --display data for all employees
'w' --write all employee data to file
'r' --read all employee data to file
'x' --exit
Enter selection: x


## Example 12.18, Page Number 616¶

In [18]:
class Distance:                      #Distance class

def __init__(self,ft=0,inc=0):   #constructor
self.__feet = ft
self.__inches = inc

def gd(d):               #get length from user  (friend function)
d._Distance__feet = input('\nEnter feet:')
d._Distance__inches = input('Enter inches:')

def sd(d):              #display distance  (friend function)
print d._Distance__feet , '\' -' , d._Distance__inches , '\"'

#define distances
dist1 = Distance()
dist2 = Distance()

#define and initialize dist3
dist3 = Distance(11,6.25)

#get dist1 and dist2 from user
print 'Enter two Distance value:',
gd(dist1)
gd(dist2)

#display all lengths
print '\ndist1 = ',;sd(dist1)
print 'dist2 = ',;sd(dist2)
print 'dist3 = ',;sd(dist3)

Enter two Distance value:
Enter feet:10
Enter inches:3.5

Enter feet:12
Enter inches:6

dist1 =  10 ' - 3.5 "
dist2 =  12 ' - 6 "
dist3 =  11 ' - 6.25 "


## Example 12.19, Page Number 618¶

In [19]:
from pickle import dump,load

class Distance:                      #Distance class

def __init__(self,ft=0,inc=0):   #constructor
self.__feet = ft
self.__inches = inc

def gd(d):               #get length from user  (friend function)
d._Distance__feet,dummy,dummy,d._Distance__inches,dummy = input(),raw_input(),raw_input(),input(),raw_input()

def sd(d):              #display distance  (friend function)
print d._Distance__feet , '\' -' , d._Distance__inches , '\"'

dist1 = Distance()
ofile = open('Dist.txt','w')           #create and open a file

z=0
while True:
print 'Enter Distance:'
gd(dist1)                    #get distance from user
dump(dist1,ofile)     #write it to file
z += 1
ch = raw_input("Enter another person (y/n)? ")
if(ch == 'n'):
break

ofile.close()          #close file

ifile = open('Dist.txt','r')        #open same file in read mode

print '\nContents of disk file is:'
for j in range(z):
print 'Distance =',;sd(dist1)   #display dist

Enter Distance:
3
'
-
4.5
"
Enter another person (y/n)? y
Enter Distance:
7
'
-
11.25
"
Enter another person (y/n)? y
Enter Distance:
11
'
-
6
"
Enter another person (y/n)? n

Contents of disk file is:
Distance = 3 ' - 4.5 "
Distance = 7 ' - 11.25 "
Distance = 11 ' - 6 "


## Example 12.20, Page Number 621¶

In [20]:
                        #test data
ch = 'x'
j=77
d=67890.12345
str1 = "Kafka"
str2 = "Freud"

#print data
print 'ch =',ch
print 'j =',j
print 'd = %.2f' %d
print 'str1 =',str1
print 'str2 =',str2

ch = x
j = 77
d = 67890.12
str1 = Kafka
str2 = Freud


## Example 12.21, Page Number 622¶

In [21]:
from sys import argv

print 'argc =',len(argv)          #number of arguments

for j in range(len(argv)):        #display arguments
print 'Argument',j,'=',argv[j]

argc = 8
Argument 0 = -c
Argument 1 = -f
Argument 2 = C:\Users\Aman Jain\.ipython\profile_default\security\kernel-08538966-3f5b-48ea-8e02-714bd8abf473.json
Argument 3 = --IPKernelApp.parent_appname='ipython-notebook'
Argument 4 = --profile-dir
Argument 5 = C:\Users\Aman Jain\.ipython\profile_default
Argument 6 = --interrupt=1980
Argument 7 = --parent=1976


## Example 12.22, Page Number 623¶

In [22]:
from sys import argv

if not(len(argv)==2):
print "Format: otype filename"
else:
#Open a file
infile=open(argv[1],'r')

#In case file cannot open
if(not(infile)):
print "Cannot open file."
else:
print ch
In.close()

Format: otype filename


## Example 12.23, Page Number 625¶

In [23]:
s1 = "\nToday's winning number is "
n1 = "17982"

outfile = open("PRN1.txt",'w')     #open the file

#send data to file
outfile.write(s1)
outfile.write(n1)
outfile.write("\x0C")

outfile.close()


## Example 12.24, Page Number 625¶

In [24]:
from sys import argv

if not(len(argv)==2):
print "Format: otype filename"
else:
#Open a file
infile=open(argv[1],'r')

#In case file cannot open
if(not(infile)):
print "Cannot open file."
else:
outfile = open("PRN1.txt")

Format: otype filename