Simple Programs - File Handling
Simple Programs - File Handling
Class 12
[1] Create a text file “intro.txt” in python and ask the user
to write a single line of text by user input.
def program1():
f = open("intro.txt","w")
text=input("Enter the text:")
f.write(text)
f.close()
program1()
[2] Create a text file “MyFile.txt” in python and ask the user
to write separate 3 lines with three input statements from
the user.
def program2():
f = open("MyFile.txt","w")
line1=input("Enter the text:")
line2=input("Enter the text:")
line3=input("Enter the text:")
new_line="\n"
f.write(line1)
f.write(new_line)
f.write(line2)
f.write(new_line)
f.write(line3)
f.write(new_line)
f.close()
program2()
[3] Write a program to read the contents of both the files
created in the above programs and merge the contents
into “merge.txt”. Avoid using the close() function to close
the files.
def program3():
with open("MyFile.txt","r") as f1:
data=f1.read()
with open("intro.txt","r") as f2:
data1=f2.read()
with open("merge.txt","w") as f3:
f3.write(data)
f3.write(data1)
program3()
In the next section of Python File Handling Programs Class 12
you will find programs based on counting letters.
[4] Count the total number of upper case, lower case, and
digits used in the text file “merge.txt”.
def program4():
with open("merge.txt","r") as f1:
data=f1.read()
cnt_ucase =0
cnt_lcase=0
cnt_digits=0
for ch in data:
if ch.islower():
cnt_lcase+=1
if ch.isupper():
cnt_ucase+=1
if ch.isdigit():
cnt_digits+=1
print("Total Number of Upper Case letters are:",cnt_ucase)
print("Total Number of Lower Case letters are:",cnt_lcase)
print("Total Number of digits are:",cnt_digits)
program4()
[5] Write a program to count a total number of lines and
count the total number of lines starting with ‘A’, ‘B’, and
‘C’. (Consider the merge.txt file)
def program5():
with open("merge.txt","r") as f1:
data=f1.readlines()
cnt_lines=0
cnt_A=0
cnt_B=0
cnt_C=0
for lines in data:
cnt_lines+=1
if lines[0]=='A':
cnt_A+=1
if lines[0]=='B':
cnt_B+=1
if lines[0]=='C':
cnt_C+=1
print("Total Number of lines are:",cnt_lines)
print("Total Number of lines strating with A are:",cnt_A)
print("Total Number of lines strating with B are:",cnt_B)
print("Total Number of lines strating with C are:",cnt_C)
program5()
[6] Find the total occurrences of a specific word from a text
file:
def program6():
cnt = 0
word_search = input("Enter the words to search:")
with open("merge.txt","r") as f1:
for data in f1:
words = data.split()
for word in words:
if (word == word_search):
cnt+=1
print(word_search, "found ", cnt, " times from the file")
program6()
Python File Handling Programs based on read(), readline() and
readlines() functions.
[7] Read first n no. letters from a text file, read the first line,
read a specific line from a text file.
def program7():
cnt = 0
n = int(input("Enter no. characters to read:"))
with open("merge.txt","r") as f1:
line1=f1.readline()
print("The first line of file:",line1)
nchar=f1.read(n)
print("First n no. of characters:", nchar)
nline=f1.readlines()
print("Line n:",nline[n])
program7()
Now let us see Programs based on replace contents. in Python
File Handling Programs Class 12
[8] Replace all spaces from text with – (dash).
def program8():
cnt = 0
n = int(input("Enter no. characters to read:"))
with open("merge.txt","r") as f1:
data = f1.read()
data=data.replace(' ','-')
with open("merge.txt","w") as f1:
f1.write(data)
program8()
Below are some Programs based on tell() and seek() functions
in Python File Handling Programs Class 12.
[9] Write a program to know the cursor position and print
the text according to below-given specifications:
1. Print the initial position
2. Move the cursor to 4th position
3. Display next 5 characters
4. Move the cursor to the next 10 characters
5. Print the current cursor position
6. Print next 10 characters from the current cursor position
def program9():
f = open("merge.txt","r")
print(f.tell())
f.seek(4,0)
print(f.read(5))
f.seek(10,0)
print(f.tell())
print(f.seek(7,0))
print(f.read(10))
program9()
In the next section of Python File Handling Programs Class 12
you will find programs based on high-order thinking skills.
[10] Append the contents in entered by the user in the text
file:
def program10():
text = input("Enter text to append in the file:")
with open("merge.txt","a") as f1:
f1.write(text)
program10()
[11] Read the contents of file in reverse order:
def program11():
for i in reversed(list(open("merge.txt","r"))):
print(i.rstrip())
program11()
[12] Replace multiple spaces with single space in a text
file.
def program12():
f1 = open("merge.txt","rt")
f2 = open("merge1.txt","wt")
for line in f1:
f2.write(' '.join(line.split()))
f1.close()
f2.close()
program12()
Method 2:
import re
def program12():
f1 = open("merge.txt","rt")
f2 = open("merge3.txt","wt")
for line in f1:
f2.write(re.sub('\s+',' ',line))
f1.close()
f2.close()
program12()
In the next section of Python File Handling Programs Class 12
you will find a suggested practical list of programs given in the
CBSE curriculum document.
[1] Read a text file line by line and display each word
separated by a #.
f=open("MyFile.txt")
d=f.read()
s=''
for i in d:
s+=i.replace(' ','#')
print(s)
f.close()
[2] Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the
file.
f=open("MyFile.txt")
d=f.read()
v=0
c=0
u=0
l=0
for i in d:
if i.isupper():
u+=1
elif i.islower():
l+=1
if i.lower() in 'aeiou':
v+=1
elif i.isspace():
pass
elif i.lower() not in 'aeiou':
c+=1
print("Vowels:",v)
print("Consonants:",c)
print("Uppers:",u)
print("Lowers:",l)
f.close()
[3] Remove all the lines that contain the character ‘a’ in a
file and write it to another file.
f1=open("MyFile.txt")
f2=open("Temp.txt",'w')
l=f1.readlines()
for i in l:
if 'a' not in i:
f2.write(i)
f1.close()
f2.close()