0% found this document useful (0 votes)
327 views6 pages

Text File Programs Xii C

This document provides examples of using Python to read from and write to text files. It demonstrates opening files in read ('r'), write ('w'), and append ('a') modes. Methods like read(), readlines(), write(), and writelines() are used to read from and write to files. Examples include counting characters, words, and lines in files and filtering or modifying file contents.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
327 views6 pages

Text File Programs Xii C

This document provides examples of using Python to read from and write to text files. It demonstrates opening files in read ('r'), write ('w'), and append ('a') modes. Methods like read(), readlines(), write(), and writelines() are used to read from and write to files. Examples include counting characters, words, and lines in files and filtering or modifying file contents.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

TEXT FILE PROGRAMS

 For opening a file to read some data from it, use ‘r’ mode.
 Then use read(), readlines() or readline() method to read data from it.
 For creating a file and write something to it use ‘w’ or ‘a’ mode.
 Then use write() or writelines() method to write data into it.
 To add some more lines to an existing file without losing the previous
contents, use ‘a’ mode. (Append mode)

 SYNTAX FOR OPENING A FILE


Fileobject=open(“location of the file with name”, “opening mode”)

 EXAMPLES WITH READ() AND READLINES() FUNCTIONS AND WRITE()


AND WRITELINE()

#Program to read all lines into a list (using readlines())


def fileread():
f =open("d:\\xiic\\test.txt",'r')
lines =f.readlines()
for line in lines:
print(line,end=' ')
f.close()
=======================================================
#Program to count number of ‘me’ or ‘my’ in a text file story.txt
def countwords():
f=open("D:\\xiic\\story.txt","r")
count=0
lst=f.read()
for i in lst.split():
if i.upper()=="Me".upper() or i.upper()=="My".upper():
count=count+1
print ("Number of me or my is", count)
countwords()
.............................................................................................................'''
#Program to count number of ‘A’ or ‘M’ in a text file story.txt
def countAM():
f=open("D:\\xiic\\story.txt","r")
countA=0
countM=0
CON=f.read()
for i in CON:
if i.upper()=='A':
countA=countA+1
elif i.upper()=='M':
countM=countM+1
print("Number of A is ",countA,"\nNumber M is:",countM)
countAM()
====================================================
#Program to count number of lines starting with ‘M’
def countlines():
f=open("D:\\xiic\\story.txt","r")
countl=0
LN=f.readlines()
for i in LN:
if i[0]=="M":
countl+=1
print("Number of lines starting with M=",countl)
countlines()
====================================================
#Program to print lines not staring with a vowel from a text file TESTFILE.TXT
def COUNTLINES() :
file = open ('TESTFILE.TXT', 'r')
lines = file.readlines()
count=0
for w in lines :
if (w[0]).lower() not in 'aeoiu':
count = count + 1
print ("The number of lines not starting with any vowel: ", count)
file.close()
COUNTLINES()
Write a function ETCount() in Python, which should read each character of a
text file “TESTFILE.TXT” and then count and display the count of occurrence
of alphabets E and T individually (including small cases e and t too)
def ETCount() :
file = open ('TESTFILE.TXT', 'r')
lines = file.read()
countE=0
countT=0
for ch in lines :
if ch in 'Ee':
countE = countE + 1
if ch in 'Tt':
countT=countT + 1
print ("The number of E or e : ", countE)
print ("The number of T or t : ", countT)
file.close()
ETCount()
#Program to count the word “AND” in a text file STORY.TXT.
def COUNT_AND( ):
count=0 file=open(‘STORY.TXT','r')
line = file.read() ( readlines() also can be used)
word = line.split()
for w in word:
if w in [‘AND’,’and’,’And’]:
count=count+1
print(“Number of word And is”, count)
file.close()
print(count)
==================================================
#Write a function in Phyton to read lines from a text file visiors.txt, and
display only those lines, which are starting with an alphabet 'P'.
def rdlines():
file = open('visitors.txt','r')
lines=file.readlines()
for line in lines:
if line[0] == 'P':
print(line)
file.close()
rdlines()
#Write a method in Python to read lines from a text file book.txt, to find and
display the occurrence of the word 'are'.
def countare():
count=0
file = open('book.txt','r')
lines=file.readlines()
for line in lines:
for wrd in line.split():
if wrd == 'are':
count+=1
print(“number of are is=”, count)
file.close()
rdlines()
#Write a method/function DISPLAYWORDS() in python to read lines from a
text file STORY.TXT, and display those words, which are less than 4
characters.
def displaywords():
f = open("story.txt","r"):
d = f.readlines()
for i in d:
for j in d.split():
if (len (j)<4:
print(j)
displaywords():

====================================================================
#Write a function RevText() to read a text file "Story.txt" and Print only word
starting with 'I' in reverse order. Example: If value in text file is: INDIA IS MY
COUNTRY Output will be: AIDNI SI MY COUNTRY
def revtext():
f=open("sorty.txt","r")
s=""
while True:
d=f.readline()
if not d:
break
else:
m=d.split()
for i in m:
if i[0]=='i' or i[0]=='I':
s=s+" "+(i[::-1])
else:
s=s+" "+i
print(s)
s=""
revtext()

============================================================
#To print the digits in a file ( CHARACTER BY CHARACTER READING)
def fileread():
f =open("d:\\xiic\\test.txt",'r')
str=f.read()
for i in str:
if i.isdigit():
print("\nDigits are=",i)
f.close()
fileread()
================================================
#To print some characters from file
f =open("d:\\xiic\\test.txt",'r')
str=f.read(4)
print(str)
=================================================

#To append into the file


f =open("d:\\xiic\\test.txt",'a')
str=input("What do you want to write into the file? =")
f.write(str)
f.close()
fileread()
================================================
#To use writelines() to write into a file
f =open("d:\\xiic\\test.txt",'a')
lst =["\nComputer Science\n","Physics\n","Chemistry\n","Maths"]
f.writelines(lst)
f.close()
fileread()
#Program to accept input from user and write into text file.
filename = input("Enter the name of the file to write to: ")
with open(filename, "w") as file:
while True:
line = input("Enter a line of text (or 'exit' to quit): ")
if line == "exit":
break
file.writelines(line + "\n")
==============================================================
#Program to write dictionary details into a text file output.txt
my_dict = {"name": "John", "age": 25, "city": "New York"}
with open("output.txt", "w") as file:
for key, value in my_dict.items():
file.writelines(f"{key}: {value}\n") (f--write in key value pair format)

with open("output.txt", "r") as file:


print(file.readlines())
======================================================
# Program for frequency of words
wordcount=0
f=open("Walker.txt",'r')
for line in f:
wordcount+=len(line.split())
print("Number of Words:",wordcount)
f.close()
============================================================
#Program to remove lines starting with @ and write it into another file
def filter():
fin=open("d:\\xiic\\source.txt","r")
fout=open("d:\\xiic\\newfile2.txt","w")
text=fin.readlines()
for i in text:
if i[0]!="@":
fout.write(i)
fin.close()
fout.close()
def showcontent():
fin=open("d:\\xiic\\newfile2.txt","r")
text=fin.read()
print(text)
fin.close()
filter()
showcontent()

You might also like