FileHandringPractical Questions Python
FileHandringPractical Questions Python
file1=open('file1.txt','r')
lines=file1.readlines()
file2=open('file2.txt','w')
for line in lines:
if line[0]=='p' or line[0]=='P':
file2.write(line)
file1.close()
file2.close()
Q2. Write a program to count and display the no of lines starting with
‘S’ present in a text file “lines.txt”.
sol.
myfile=open('lines.txt','r')
lines=myfile.readlines()
count=0
for line in lines:
if line[0]=='S' or line[0]=='s':
count+=1
myfile.close()
print("Number of lines starting with 'S' are",count)
Q3. Write a method/function DISPLAYVOWEL() in python to read lines
from a text file STORY.TXT, and display those words, which start with a
vowel(small or capital).
def DISPLAYVOWEL():
vowels=['a','e','i','o','u','A','E','I','O','U']
myfile=open('STORY.TXT','r')
words=myfile.read().split()
for word in words:
if word[0] in vowels :
print(word[0])
myfile.close()
Q4. Write a function in python to count the number of lines in a text file
‘STORY.TXT’ which are ending with an alphabet ‘e’ .
def countende():
myfile=open('STORY.TXT','r')
lines=myfile.readlines()
count=0
for line in lines:
if line[-1]=='\n':
if line[-2]=='e' or line[-2]=='E':
count+=1
elif line[-1]=='e' or line[-1]=='E':
count+=1
myfile.close()
print("Number of lines ending with 'e' are",count)
Q5. Write a function remove_lowercase( ) that accepts two filenames,
and copies all lines that do not start with a lowercase letter from the
first file into the second.
def remove_lowercase(file1,file2):
myfile1=open(file1,'r')
myfile2=open(file2,'w')
lines=myfile1.readlines()
for line in lines:
if line[0].isupper():
myfile2.write(line)
myfile1.close()
myfile2.close()