Chapter 11: Files

Example 1 , Page number: CP-277

In [1]:
# Program to create a text file

fp = open("sample.txt","w") # open file in write mode

print "Type the text and Press enter key at end."
print
print "Computer Programming in C language is widely used for Science and Engineering applications"
# input data to file
ch = ['Computer ','Programming ','in ','C ','language ','is ','widely ','used ','for ','Science ','and ' ,'Engineering ','applications.']
for i in ch:
    fp.write(i)
fp.close()
    
Type the text and Press enter key at end.

Computer Programming in C language is widely used for Science and Engineering applications

Example 2, Page Number: CP-278

In [3]:
# Program to read text file and count number of vowels

fp = open("sample.txt","r") # open file in read mode
count = 0
print "The Content of the file is:"

while (1):    
    ch = fp.read(1)
    if not ch:
        break
    print ch
    # switch statements
    if ch == "A" or ch == "a":  # case 'A' or 'a'
        count = count + 1
    elif ch == "E" or ch == "e": # case 'E' or 'e'
        count = count + 1
    elif ch == "I" or ch == "i": # case 'I' or 'i'
        count = count + 1
    elif ch == "O" or ch == "o": # case 'O' or 'o'
        count = count + 1
    elif ch == "U" or ch == "u": # case 'U' or 'u'
        count = count + 1



fp.close()    
print "Number of vowels present =",count    
    
The Content of the file is:
C
o
m
p
u
t
e
r
 
P
r
o
g
r
a
m
m
i
n
g
 
i
n
 
C
 
l
a
n
g
u
a
g
e
 
i
s
 
w
i
d
e
l
y
 
u
s
e
d
 
f
o
r
 
S
c
i
e
n
c
e
 
a
n
d
 
E
n
g
i
n
e
e
r
i
n
g
 
a
p
p
l
i
c
a
t
i
o
n
s
.
Number of vowels present = 31