Chapter 13: Persistent Data: File Input and Output

example 13.1, page no. 296

In [4]:
try:
    if(fp):
        print "infile = ", fp
        print "0"
except IOError:
    print "1"
1

example 13.2, page no. 296

In [2]:
try:
    fp = open("students.dat", "w")
    if(fp):
        print "infile = ", fp
        print "0"
except IOError:
    print "1"
infile =  <open file 'students.dat', mode 'w' at 0x2d80a50>
0

example 13.3, page no. 299

In [3]:
fp = open("students.dat", "w")
print "Writing to the file"
print "==================="
print "Enter class name: ",
data = raw_input()
fp.write(data)
fp.write("\n")
print "Enter number of students: ",
data = raw_input()
fp.write(data)
fp.close()
Writing to the file
===================
Enter class name: C++
 Enter number of students: 32

example 13.4, page no. 301

In [4]:
fp = open("students.dat", "w")
print "Writing to the file"
print "==================="
print "Enter class name: ",
data = raw_input()
fp.write(data)
fp.write("\n")
print "Enter number of students: ",
data = raw_input()
fp.write(data)
fp.close()
fp = open("students.dat", "r")
print "Reading from the file"
print "====================="
lines = fp.readlines()
for line in lines:
    print line
fp.close()
Writing to the file
===================
Enter class name: C++
 Enter number of students: 32
 Reading from the file
=====================
C++

32

example 13.5, page no. 303

In [5]:
fp = open("students.dat", "w")
print "Writing to the file"
print "==================="
print "Enter class name: ",
data = raw_input()
fp.write(data)
fp.write("\n")
print "Enter number of students: ",
data = raw_input()
fp.write(data)
fp.close()
fp = open("students.dat", "r")
print "Reading from the file"
print "====================="
lines = fp.readlines()
for line in lines:
    print line
fp.close()
Writing to the file
===================
Enter class name: C++
 Enter number of students: 32
 Reading from the file
=====================
C++

32

example 13.6, page no. 305

In [6]:
fp = open("students.dat", "w")
print "Writing to the file"
print "==================="
print "Enter class name: ",
data = raw_input()
fp.write(data)
fp.write("\n")
print "Enter number of students: ",
data = raw_input()
fp.write(data)
fp.close()
fp = open("students.dat", "r")
print "Reading from the file"
print "====================="
while(fp.readline()):
    print fp.readline()
Writing to the file
===================
Enter class name: C++
 Enter number of students: 32
 Reading from the file
=====================
32
In [ ]: