0% found this document useful (0 votes)
3 views

DataFileHandling

Notes

Uploaded by

VEDISH SHARMA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

DataFileHandling

Notes

Uploaded by

VEDISH SHARMA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

DATA FILE HANDLING – TEXT FILE

1 Write a function to read total no. of This or this in a file

def Countthis():
f=open("Read.txt",'r')
data=f.read()
word=data.split()#By default by space and return string into list
c=0
for i in word:
if i=='this' or i=='This':
c+=1
print(c)
Countthis()
2 #Write a function to read total no. of words of lenght>5 in a file

def Length():
f=open("Read.txt",'r')
data=f.read()
word=data.split()#By default split by space
#and return string into list
c=0
for i in word:
if len(i)>5:
c+=1
print(c)
Length()
3 #read file line by line and display number of line and each line

def count():
f=open("first.txt",'r')
c1=0
while True:
d=f.readline()
if d=='':#no space
break
else:
c1+=1
print(d)
print(c1)
count()

4 #read file line by line and display number of line starting with E and T
def BeginE():
f=open("first.txt",'r')
c=0
d=f.readlines()
for i in d:
if i[0]=='E' or i[0]=='T':
c+=1

print(i)
print(c)
BeginE()
#read file line by line and display line whose lenght is greater than 15
def count15():
f=open("first.txt",'r')
c=0
d=f.readlines()
for i in d:
if len(i)>15:
c+=1
print(i)
print(c)
count15()
5 WAP to write file using writelines

with open("sq.txt","w") as f:
d=["Computer Science","\nchemistry","\nPhysics"]
f.writelines(d)

6 WAP TO COPY CONTENT OF ONE FILE INTO ANOTHER FILE

#METHOD 1 - BY USING read() function and with(open) method


with open("first.txt","r") as f1:
d=f1.read()
print(d)
with open("second.txt","w") as f2:
f2.write(d)

#METHOD 2 - BY USING read() function


f1=open("p.txt",'r')
d=f1.read()
f2=open("q.txt",'w')
f2.write(d)
f1.close()
f2.close()

#METHOD 3 - BY USING readline() function


f1=open("first.txt","r")
f2=open("second.txt","w")
while True:
d=f1.readline()
if d=='':
break
else:
f2.write(d)
f1.close()
f2.close()
#METHOD 4 - BY USING readlines() function
f1=open("first.txt","r")
f2=open("second.txt","w")
d=f1.readlines()
for a in d:
f2.write(a)
f1.close()
f2.close()

You might also like