Obs Prg2024
Obs Prg2024
TEXT FILE
1. Write a method in python to write multiple line of text contents into a text file
mylife.txt.
def writelines():
outfile = open('myfile.txt','w')
while True:
line = input('Enter line: ')
line += '\n'
outfile.write(line)
choice = input('Are there more lines y/n? ')
if choice == 'n':
break
outfile.close()
2. Write a function in Python to read lines from a text file diary.txt, and display
only those lines, which are starting with an alphabet 'P'.
def readlines():
file = open('diary.txt','r')
for line in file:
if line[0] == 'P':
print(line)
file.close()
India is the fastest-growing economy. India is looking for more investments around the
globe. The whole world is looking at India as a great market. Most of the Indians can
foresee the heights that India is capable of reaching.
The output should be 4.
def count_word():
file = open('india.txt','r')
count = 0
for line in file:
words = line.split()
for word in words:
if word == 'India':
count += 1
print(count)
file.close()
4. Assuming that a text file named first.txt contains some text written into it, write
a function that reads the file first.txt and creates a new file named second.txt, to
contain only those words from the file first.txt which start with a lowercase vowel
(i.e. with 'a', 'e', 'i', 'o', 'u').
For example if the file first.txt contains: Carry umbrella and overcoat when it rains
Then the file second.txt shall contain: umbrella and overcoat it
def copy_file():
infile = open('first.txt','r')
outfile = open('second.txt','w')
5. Write a function in Python to count and display number of vowels in text file.
def count_vowels():
infile = open('first.txt','r')
count = 0
data = infile.read()
for letter in data:
if letter in 'aeiouAEIOU':
count += 1
print('Number of vowels are',count)
infile.close()