FILE HANDLING New
FILE HANDLING New
Computer Science
CBSE Syllabus
File Handling in Python
File handling: Need for a data file, Types of file: Text files, Binary files and CSV
(Comma separated values) files.
● Text File: Basic operations on a text file: Open (filename – absolute or relative
path, mode) / Close a text file, Reading and Manipulation of data from a text file,
Appending data into a text file, standard input / output and error streams,
relative and absolute paths.
● Binary File: Basic operations on a binary file: Open (filename – absolute or
relative path, mode) / Close a binary file, Pickle Module –methods load and
dump; Read, Write/Create, Search, Append and Update operations in a binary
file.
● CSV File: Import csv module, functions – Open / Close a csv file, Read from a
csv file and Write into a csv file using csv.reader ( ) and csv.writerow( ).
INTRODUCTION:
• File:- A file is a collection of related data stored in a particular area on the
disk.
• Stream: - It refers to a sequence of bytes.
File handling is an important part of any web application.
Data Files: The data files that store data pertaining to specific application, for
later use.
Data files can be stored in two ways:
1. Text Files: Text files are structured as a sequence of lines, where each line
includes a sequence of characters.
2. Binary Files : A binary file is any type of file that is not a text file.
EOL (End of Line), is the new line character The data is stored after converting it into
(‘\n’) in python by default. machine understandable binary language.
Opening and closing a file:
Opening a file: To work with a file, first of all you have to open the file. To open a file
in python, we use open( ) function.
The open( ) function takes two parameters; filename, and mode. open( ) function
returns a file object.
Syntax:
file_objectname= open(filename, mode)
Example:
To open a file for reading it is enough to specify the name of the file:
f = open("book.txt")
The code above is the same as:
f = open("book.txt", "rt")
Where "r" for read mode, and "t" for text are the default values, you do not need to
specify them.
Closing a file:
After performing the operations, the file has to be closed. For this, a close( )
function is used to close a file.
Syntax:
File_objectname.close( )
File Modes:
Mode Description
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default
mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This
is the default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of
the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new
file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
File Modes:
Mode Description
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist,
creates a new file for reading and writing
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file
does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append
mode. If the file does not exist, it creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file
is in the append mode. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens
in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
In addition you can specify if the file should
be handled as binary or text mode:
def fileCreation():
def fileCopy():
ofile = open("story.txt","w+") ifile = open("story.txt","r")
n=int(input("Enter number of lines : ")) ofile = open("newstory.txt","w")
l = ifile.readlines()
for i in range(n):
print (l)
line = input("enter sentence :") for i in l:
ofile.write(line) ofile.write(i)
ifile.close()
ofile.write('\n')
ofile.close()
ofile.close()
def fileDisplaying1():
for l in open("story.txt","r").readlines():
print (l,end='')
def fileDisplaying2():
for l in open("newstory.txt","r").readlines():
print(l,end=' ')
print ("\n Creating Original Text File : \n")
fileCreation()
print ("\n Making Copy of the Text File \n")
fileCopy()
print ("\n Displaying the Original File \n")
fileDisplaying1()
print ("\n Displaying the Copy of the Text File \n")
fileDisplaying2()
Output:
Displaying the Original File
Creating Original Text File :
Our Own High School
Al Warqa'a, Dubai, UAE
Enter number of lines : 2
enter sentence :Our Own High School Displaying the Copy of the Text File
enter sentence :Al Warqa'a, Dubai, UAE
Our Own High School
Al Warqa'a, Dubai, UAE
Making Copy of the Text File '
read() or This function facilitates reading the full file in the form of string. However
read(n) one can restrict the reading to a certain limit by specifying the size in this
function like read(size).
readline() This helps the user reading only the first line of the file or reading line until
it meets an EOF character in file. Suppose EOF is met at first, then an empty
string will be returned.
readlines() This function reads all lines from the file into a list; starts reading from the
cursor up to the end of the file and return a list of lines.
Example using read()
'''
Text File foo.txt:
0123456789ABCDEF
Python is a great language.
Yeah its great!!
‘‘’
# select the file from desktop, right click and copy as path and paste it
"C:\Users\yadav.s_oow\OneDrive - GEMS Education\Desktop\foo.txt“
<class 'str'>
'''
'''
Example using readline()
Text File foo.txt:
0123456789ABCDEF
Python is a great language.
Yeah its great!!
‘‘’
F=open(“C:\\Users\\yadav.s_oow\\OneDrive - GEMS Education\\Desktop\\foo.txt”,”r”)
#OR
f = open("C:/Users/yadav.s_oow/OneDrive - GEMS Education/Desktop/Python/12/File Handling/foo.txt", "r")
#OR
f = open(r"C:\Users\yadav.s_oow\OneDrive - GEMS Education\Desktop\foo.txt", ‘r')
print("\nReading the text file from the specified folder and displaying the file contents: readline() reads one line ")
print(f.readline())
'''
Output:
Reading the text file from the specified folder and displaying the file contents: readline() reads one line
0123456789ABCDEF
'''
Example using readlines()
'''
Text File foo.txt:
0123456789ABCDEF
Python is a great language.
Yeah its great!!
'''
f = open("C:/Users/yadav.s_oow/OneDrive - GEMS Education/Desktop/Python/12/File Handling/foo.txt", "r")
print("\nReading the text file from the specified folder and displaying the file contents: readlines() reads all lines ")
print(f.readlines())
'''
Output:
Reading the text file from the specified folder and displaying the file contents: readlines() reads all lines
['0123456789ABCDEF\n', 'Python is a great language.\n', 'Yeah its great!!\n']
'''
Example using readlines()
'''
Text File foo.txt:
0123456789ABCDEF
Python is a great language.
Yeah its great!!
'''
f = open("foo.txt", "r")
print("\n Reading the text file from the specified folder and displaying the file contents: readlines() reads all lines ")
x=f.readlines()
print(type(x))
print(x)
'''
Output:
Reading the text file from the specified folder and displaying the file contents: readlines() reads all lines
<class 'list'>
['0123456789ABCDEF\n', 'Python is a great language.\n', 'Yeah its great!!\n']
'''
Example: read(), seek() & tell() '''
Text File foo.txt:
fo = open("foo.txt", "r+") 0123456789ABCDEF
str = fo.read(10) Python is a great language.
Yeah its great!!
print ("Read String is : ", str) '''
print ("Length = ",len(str))
# Check current position
position = fo.tell() '''
print ("Current file position : ", position) Output:
# Reposition pointer at the beginning once again
Read String is : 0123456789
position = fo.seek(0, 0) Length = 10
str = fo.read(63) Current file position : 10
print ("Again read String is : ", str) Again read String is :
0123456789ABCDEF
# Close opened file Python is a great language.
fo.close() Yeah its great!!
'''
Q: Find output: '''
Text File foo.txt:
0123456789ABCDEF
Python is a great language.
Yeah its great!!
'''
f = open('foo.txt', 'r')
last_pos = f.tell() # get to know the current position in the file
print("Last position = ",last_pos)
last_pos = last_pos + 10
f.seek(last_pos) # to change the current position in a file
text= f.readlines(last_pos)
print (text)
'''
Output:
Last position = 0
['ABCDEF\n', 'Python is a great language.\n']
'''
Q: Find output: '''
Text File foo.txt:
0123456789ABCDEF
Python is a great language.
Yeah its great!!
'''
f = open('foo.txt', 'r')
last_pos = f.tell() # get to know the current position in the file
print("Last position = ",last_pos)
last_pos = last_pos + 10
f.seek(last_pos) # to change the current position in a file
text= f.readlines(5)
print (text)
'''
Output:
Last position = 0
['ABCDEF\n']
'''
Q: Find output: '''
Text File foo.txt:
0123456789ABCDEF
Python is a great language.
Yeah its great!!
'''
f = open('foo.txt', 'r')
last_pos = f.tell() # get to know the current position in the file
print("Last position = ",last_pos)
last_pos = last_pos + 10
f.seek(last_pos) # to change the current position in a file
text= f.readlines() # It reads from current position to the end of line
print (text)
Output:
Last position = 0
['ABCDEF\n', 'Python is a great language.\n', 'Yeah its great!!\n']
Q: Find output: '''
Text File foo.txt:
0123456789ABCDEF
Python is a great language.
Yeah its great!!
'''
f = open('foo.txt', 'r')
last_pos = f.tell() # get to know the current position in the file
print("Last position = ",last_pos)
last_pos = last_pos + 10
f.seek(last_pos) # to change the current position in a file
text= f.readlines(last_pos+10) # It reads from current position to the
#end of line
print (text)
Output:
Last position = 0
['ABCDEF\n', 'Python is a great language.\n']
Q: Find output: '''
Text File foo.txt:
0123456789ABCDEF
Python is a great language.
Yeah its great!!
'''
f = open('foo.txt', 'r')
last_pos = f.tell() # get to know the current position in the file
text= f.readlines(5) # It reads from current position to the end of line
print (text)
Output:
['0123456789ABCDEF\n']
Q: Find output: '''
Text File foo.txt:
0123456789ABCDEF
Python is a great language.
Yeah its great!!
fo = open("foo.txt", "r+") '''
str1 = fo.read(5)
print("Str=",str1)
fo.seek(8) Str= 01234
str2=fo.read(5) Str2= 89ABC
Loc= 18
print("Str2=",str2) Str3= Python is a great language.
fo.seek(18,0) Yeah its great!!
loc=fo.tell()
print("Loc=",loc)
str3=fo.read()
print("Str3=",str3)
'''
Output: Text File foo.txt:
0123456789ABCDEF
Python is a great language.
Str= 01234 Yeah its great!!
'''
Str2= 89ABC
Loc= 18
Str3= Python is a great language.
Yeah its great!!
Output:
The reference point is selected by the from_where argument. It accepts three values:
0: sets the reference point at the beginning of the file
1: sets the reference point at the current file position
2: sets the reference point at the end of the file
By default from_ where argument is set to 0.
Note: Reference point at current position / end of file cannot be set in text mode
except when offset is equal to 0.
Example 1: Let’s suppose we have to read a file named “code.txt” which contains
the following text:
"Code is like humor. When you have to explain it, it is bad."
Text File code.txt
Output:
Text File data.txt Output:
Text File data.txt Output:
Output:
Text File data.txt
Output:
Text File data.txt
tell() function in Python Files
tell()
tell() method can be used to get the position of File Handle. tell() method
returns current position of file object. This method takes no parameters and
returns an integer value. Initially file pointer points to the beginning of the
file(if not opened in append mode). So, the initial value of tell() is zero.
syntax :
file_object.tell()
Output:
Output:
Sample1.txt
# Program to :
# 1. Create Text File
# 2. Display the text file
# 3. Count two alphabets given by the user
# 4. Exit def display():
def create(): fo = open("story.txt", "r")
ofile = open("story.txt","w+") print ("\n Displaying the file contents using readlines() ")
lines = fo.readlines()
choice = True
while True: print (lines)
line = input("enter sentence :") print ( type(lines))
fo.close()
ofile.write(line)
for l in lines:
ofile.write('\n') print (l)
choice = input("want to enter more data in file Y / N")
if choice.upper() == 'N' : break
ofile.close()
def count_alphabets(): # Using readlines() function
fo = open("story.txt", "r")
print ("\n Displaying text file ") def count_alphabets(): # using read() function
lines = fo.readlines() f=open("story.txt", "r")
print ("\n Displaying text file ")
alpha1=input("Enter first alphabet to be counted : ") lines=f.read()
alpha2=input("Enter second alphabet to be counted : ") print(lines)
fo.close() alpha1=input("Enter first alphabet to be counted : ")
alpha2=input("Enter second alphabet to be counted : ")
count1=0 f.close()
count2=0 count1=0
count2=0
for l in lines:
for c in lines:
for w in l.split(): if c.upper()==alpha1.upper():
for c in w: count1=count1+1
if c.upper()==alpha2.upper():
if c.upper()==alpha1.upper(): count2=count2+1
count1=count1+1 print (alpha1," is repeated ",count1," times")
if c.upper()==alpha2.upper(): print (alpha2," is repeated ",count2," times")
count2=count2+1
print (alpha1," is repeated ",count1," times")
print (alpha2," is repeated ",count2," times")
def main():
while True:
print ("\n\n\n")
print ("==========================================")
print (" MAIN MENU ")
print ("==========================================")
print ("1. Create Text File ")
print ("2. Display the file ")
print ("3. Count two alphabets given by the user")
print ("4. Exit ")
elif ch==2:
print ("Displaying the file ")
display()
elif ch==3:
print ("Counting two alphabets in the file : ")
count_alphabets()
elif ch==4:
exit()
else:
print (' Wrong choice entered')
main()
Output:
==========================================
MAIN MENU
==========================================
1. Create Text File
2. Display the file
3. Count two alphabets given by the user
4. Exit
Enter your choice :1
Creating the text file
enter sentence :Our Own High School
want to enter more data in file Y / NY
enter sentence :Indian High School
want to enter more data in file Y / NY
enter sentence :Delhi Private School
want to enter more data in file Y / NN
==========================================
MAIN MENU
==========================================
1. Create Text File
2. Display the file
3. Count two alphabets given by the user
4. Exit
Enter your choice :2
Displaying the file
def create():
ofile = open("story.txt","w+")
choice = True
while True:
line = input("enter sentence :")
ofile.write(line)
ofile.write('\n')
choice = input("want to enter more data in file Y / N")
if choice.upper() == 'N' :
break
ofile.close()
def display():
fo = open("story.txt", "r")
print ("\n Displaying the text file contents using read() ")
str=fo.read()
print(str)
fo.close()
def display_count_lines_not_starting_with_A():
fin = open("story.txt", "r")
print ("\n Displaying the text file contents using readlines() ")
lines = fin.readlines()
print ("Lines= ",lines)
print ("Type of Lines : ",type(lines))
print ("Size=",len(lines))
fin.close()
count=0
print ("Len \t Text ")
for l in lines:
print (len(l)-1,"\t",l)
if l[0]!="A":
count=count+1
while True:
print ("\n\n\n")
print ("==========================================")
print (" MAIN MENU ")
print ("==========================================")
print ("1. Create Text File ")
print ("2. Display the file ")
print ("3. Count the number of lines not starting with 'A'")
print ("4. Exit ")
elif ch==2:
print ("Displaying the file ")
display()
elif ch==3:
print ("Count the number of lines not starting with 'A': ")
display_count_lines_not_starting_with_A()
elif ch==4:
exit()
else:
print (' Wrong choice entered')
main()
Output
==========================================
MAIN MENU
==========================================
1. Create Text File
2. Display the file
3. Count the number of lines not starting with 'A'
4. Exit
Enter your choice :1
Creating the text file
enter sentence :An outstanding Performance
want to enter more data in file Y / NY
enter sentence :Today is Monday
want to enter more data in file Y / NY
enter sentence :Arabic is easy language
want to enter more data in file Y / NN
==========================================
MAIN MENU
==========================================
1. Create Text File
2. Display the file
3. Count the number of lines not starting with 'A'
4. Exit
Enter your choice :2
Displaying the file
Today is Monday
Example:
If the file content is as follows:
count= 18
# Counting characters other than alphabets and digits (Text File foo.txt)
import os 0123456789ABCDEF
Python is a great language.
def CharCount():
Yeah its great!!
count=0
if os.path.isfile("foo.txt"):
with open("foo.txt", "r") as f1:
#print(type(f1))
for line in f1:
print(line)
for char in line:
if not char.isalnum() and char!='\n': OUTPUT:
count+=1
print("Count = ", count) 0123456789ABCDEF
Python is a great language.
CharCount()
Yeah its great!!
# f=open("C:\Users\yadav.s_oow\OneDrive - GEMS
# Education\Desktop\foo.txt",'r') Count = 9
Creating Text File Using writelines()
def create_file():
outFile=open('diary.txt',"w")
List=["School Diary\n","Home Work\n","Time Table\n","Assignments\n"]
outFile.writelines(List)
print("List of lines written to the text file successfully")
outFile.close()
create_file()
print('Reading Text File: First Method')
def read_file1():
inFile = open('diary.txt', "r")
str=inFile.read()
print(str)
read_file1()
Output:
List of lines written to the text file successfully
Reading Text File: First Method
School Diary
Home Work
Time Table
Assignments
Using writelines and readline() function
def create_file1():
outFile=open('daynote.txt',"w")
List=["Mathematics\n","Physics\n","Computer Science\n"]
outFile.writelines(List)
print("List of lines written to the textfile successfully")
outFile.close()
print()
create_file1()
print('Reading Text File: using readline() Method')
def read_file():
inFile = open('daynote.txt', "r")
str=True # or str=" "
while str:
str=inFile.readline()
print(str)
inFile.close()
read_file()
Output:
Physics
Computer Science
Q: Write a menu driven programs to perform the following operations on
a text file.
4 (b) Write a method in python to read lines from a text file MYNOTES.TXT, and
display those lines, which are starting with an alphabet ‘K’. (2 marks)
rb+ Opens a file for both reading and writing in binary format. The file
pointer placed at the beginning of the file.
while True:
print ("\n\n\n")
print ("==========================================")
print (" MAIN MENU ")
print ("==========================================")
print ("1. Create Text File ")
print ("2. Display the file ")
print ("3. Counting Uppercase and Lowercase alphabets")
print ("4. Exit ")
elif ch==2:
print( "Displaying the file ")
display()
elif ch==3:
print ("Counting Uppercase and Lowercase alphabets ")
display_count_upper_lower_case()
elif ch==4:
exit()
else:
print(' Wrong choice entered')
main()
Output
==========================================
MAIN MENU
==========================================
1. Create Text File
2. Display the file
3. Counting Uppercase and Lowercase alphabets
4. Exit
Enter your choice :1
Creating the text file
enter sentence :Our Own
want to enter more data in file Y / NY
enter sentence :High School
want to enter more data in file Y / NN
==========================================
MAIN MENU
==========================================
1. Create Text File
2. Display the file
3. Counting Uppercase and Lowercase alphabets
4. Exit
Enter your choice :2
Displaying the file
def create():
ofile = open("story.txt","w+")
choice = True
while True:
line = input("enter sentence :")
ofile.write(line)
ofile.write('\n')
choice = input("want to enter more data in file Y / N")
if choice.upper() == 'N' : break
ofile.close()
def display():
fo = open("story.txt", "r")
print ("\n Displaying the text file contents using read() ")
str=fo.read()
print(str)
fo.close()
def count_word():
fo = open("story.txt", "r")
print ("\n Displaying each character of the the text file in separate lines ")
lines = fo.readlines()
word1=input("Enter first word to be counted : ")
word2=input("Enter second word to be counted : ")
fo.close()
count1=0
count2=0
for Line in lines:
for w in Line.split():
if w.upper()==word1.upper():
count1=count1+1
if w.upper()==word2.upper():
count2=count2+1
print (word1," is repeated ",count1," times")
print (word2," is repeated ",count2," times")
def main():
while True:
print ("\n\n\n")
print ("==========================================")
print (" MAIN MENU ")
print ("==========================================")
print ("1. Create Text File ")
print ("2. Display the file ")
print ("3. Counting two words given by the user ")
print ("4. Exit ")
ch = int(input('Enter your choice :'))
if ch==1:
print ("Creating the text file ")
create()
elif ch==2:
print ("Displaying the file ")
display()
elif ch==3:
print ("Counting two words in the file : ")
count_word()
elif ch==4:
exit()
else:
print (' Wrong choice entered')
main()
Output:
==========================================
MAIN MENU
==========================================
1. Create Text File
2. Display the file
3. Counting two words given by the user
4. Exit
Enter your choice :1
Creating the text file
enter sentence :Our Own High School
want to enter more data in file Y / NY
enter sentence :Delhi Private High School
want to enter more data in file Y / NN
==========================================
MAIN MENU
==========================================
1. Create Text File
2. Display the file
3. Counting two words given by the user
4. Exit
Enter your choice :2
Displaying the file
def create():
ofile = open("story.txt","w+")
choice = True
while True:
line = input("enter sentence :")
ofile.write(line)
ofile.write('\n')
choice = input("want to enter more data in file Y / N")
if choice.upper() == 'N' : break
ofile.close()
def display():
fo = open("story.txt", "r")
print ("\n Displaying the text file contents using read() ")
str=fo.read()
print(str)
fo.close()
def display_each_word_in_separate_lines():
fo = open("story.txt", "r")
print ("\n Displaying each word of the text file in separate lines ")
lines = fo.readlines()
fo.close()
words=0
for Line in lines:
for w in Line.split():
print (w)
words=words+1
print ("Number of words = ",words)
def display_each_char_in_separate_lines():
fo = open("story.txt", "r")
print ("\n Displaying each character of the the text file in separate lines ")
lines = fo.readlines()
fo.close()
for Line in lines:
for w in Line.split():
for ch in w:
print (ch)
def read_display_file_backwards():
fo = open("story.txt", "r")
print ("\n Displaying the text file contents backwards ")
lines = fo.readlines()
print ("Lines : ", lines)
size=len(lines)
print ("Number of lines =",size)
fo.close()
for i in range(size-1,-1,-1):
print (lines[i][::-1])
def main():
while True:
print ("\n\n\n")
print ("==========================================")
print (" MAIN MENU ")
print ("==========================================")
print ("1. Create Text File ")
print ("2. Display the file ")
print ("3. Read and display file Backwards ")
print ("4. Display each character in separate line ")
print ("5. Display each word in separate line ")
print ("6. Exit ")
ch = int(input('Enter your choice :'))
if ch==1:
print ("Creating the text file ")
create()
elif ch==2:
print ("Displaying the file ")
display()
elif ch==3:
read_display_file_backwards()
elif ch==4:
display_each_char_in_separate_lines()
elif ch==5:
display_each_word_in_separate_lines()
elif ch==6:
exit()
else:
print (' Wrong choice entered')
main()
Output:
==========================================
MAIN MENU
==========================================
1. Create Text File
2. Display the file
3. Read and display file Backwards
4. Display each character in separate line
5. Display each word in separate line
6. Exit
Enter your choice :1
Creating the text file
enter sentence :Our Own
want to enter more data in file Y / NY
enter sentence :High School
want to enter more data in file Y / NN
==========================================
MAIN MENU
==========================================
1. Create Text File
2. Display the file
3. Read and display file Backwards
4. Display each character in separate line
5. Display each word in separate line
6. Exit
Enter your choice :2
Displaying the file
High School
==========================================
MAIN MENU
==========================================
1. Create Text File
2. Display the file
3. Read and display file Backwards
4. Display each character in separate line
5. Display each word in separate line
6. Exit
Enter your choice :3
loohcS hgiH
nwO ruO
==========================================
MAIN MENU
==========================================
1. Create Text File
2. Display the file
3. Read and display file Backwards
4. Display each character in separate line
5. Display each word in separate line
6. Exit
Enter your choice :5
1)append record
2)insert new record (if position is given)
3)delete a record (if position is given)
4)modify the record (if position is given)
5)display the details
6)delete a record (if data is given)
7)modify the record (if data is given)
8)search record
CBSE-1. Read a text file line by line and display each
word separated by a #.
Output:
CBSE-2. Read a text file and display the number of vowels,
consonants, uppercase, lowercase characters in the file.
Output:
CBSE-3. Create a binary file with name and roll number.
Search for a given roll number and display the name,
if not found display appropriate message.
(Using list of Dictionaries)
Output:
CBSE-4. Create a binary file with roll number, name and marks.
Input a roll number and update the marks.
CBSE-5. Remove all the lines that contain the character
'a' in a file and write it to another file.
Output:
CBSE-6. Write a random number generator that generates
random numbers between 1 and 6 (simulates a dice).
CBSE-7: Menu-driven: Write a Python program to implement a
stack and queue using a list data-structure.
CBSE-8. Take a sample of ten phishing e-mails (or any text file)
and find most commonly occurring word(s)
In general, the separator character is called a delimiter, and the comma is not
the only one used. Other popular delimiters include the tab (\t), colon (:) and
semi-colon (;) characters. Properly parsing a CSV file requires us to know which
delimiter is being used
Where Do CSV Files Come From?
• CSV files are normally created by programs that handle large amounts of
data. They are a convenient way to export data from spreadsheets and
databases as well as import or use it in other programs. For example, you
might export the results of a data mining program to a CSV file and then
import that into a spreadsheet to analyze the data, generate graphs for a
presentation, or prepare a report for publication.
• CSV files are very easy to work with programmatically. Any language that
supports text file input and string manipulation (like Python) can work with
CSV files directly.
CSV (Comma Separated Values File)
# Write a program to perform read and write operation with .csv file.
import csv
def readcsv():
with open('data.csv','rt')as f:
data = csv.reader(f) #reader function to generate a reader object
for row in data:
print(row)
def writecsv():
with open('data.csv', mode='a', newline='') as file:
writer = csv.writer(file, delimiter=',', quotechar='"')
#write new record in file
writer.writerow(['4', 'Devansh', 'Arts', '404'])
print(“Enter 1 to Read Data or Enter 2 to Write data: ")
a=int(input())
if a==1:
readcsv()
elif a==2:
writecsv()
print("The write operation successful !")
print("Data.csv is written in Excel file")
else:
print("Invalid value")
Output:
Press-1 to Read Data and Press-2 to Write data:
2
The write operation successful !
Data.csv is written in Excel file
>>>
fin=open("story.txt",'r') Output:
str=fin.read( ) File contents are as follows:
Our Own
print("File contents are as follows: ")
High School
print(str)
count=0 The text file has : 16 characters
for i in str:
if i!=' ' and i!='\n':
count=count+1
print("The text file has : ", count," characters. ")
fin.close()
Programs: Check if file exists, then delete it else display message
it does not exist
import os
Output:
ch=''
if os.path.exists("sample.txt"): The file exists !
print("The file exists ! ") Do you want to delete (Y/N) ? N
print(“Do you want to delete (Y/N) ?”) File not deleted !
ch=input() >>>
if ch.upper()=='Y':
os.remove("sample.txt") The file exists !
print("The file deleted !") Do you want to delete (Y/N) ? Y
else: The file deleted !
print ("File not deleted ! ")
>>>
else: The file does not exist
print("The file does not exist")
Find Output:
f = open("story.txt", "r")
print("Name of the File: ", f.name)
print("File-Mode : ", f.mode)
print("File encoding format : ", f.encoding)
print("Is File closed? ", f.closed)
f.close()
print("Is File closed? ", f.closed)
Output:
HELLO USER!
PYTHON
FILES
Here's how we do it
Basic Usage of csv.writer() import csv
Example 1: Write into CSV files with csv.writer() with open('innovators.csv', 'w', newline='') as file:
Suppose we want to write a CSV file with the writer = csv.writer(file)
following entries: writer.writerow(["SN", "Name", "Contribution"])
writer.writerow([1, "Linus Torvalds", "Linux Kernel"])
SN,Name,Contribution
writer.writerow([2, "Tim Berners-Lee", "World Wide Web"])
1,Linus Torvalds,Linux Kernel writer.writerow([3, "Guido van Rossum", "Python
2,Tim Berners-Lee,World Wide Web Programming"])
3,Guido van Rossum,Python Programming
def readcsv():
with open('innovators.csv','rt')as f:
data = csv.reader(f) #reader function to generate a reader
Output: object
<class '_csv.reader'> print(type(data))
data= <_csv.reader object at 0x03DC8300>
print("data=",data)
['SN', 'Name', 'Contribution']
['1', 'Linus Torvalds', 'Linux Kernel'] for row in data:
['2', 'Tim Berners-Lee', 'World Wide Web'] print(row)
['3', 'Guido van Rossum', 'Python readcsv()
Programming']
Example 2: Writing Multiple Rows with writerows()
If we need to write the contents of the 2-dimensional list to a CSV file, here's
how we can do it.
import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('protagonist.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(row_list)
def readcsv():
with open('protagonist.csv','rt')as f:
data = csv.reader(f) #reader function to generate a reader object
print(type(data))
print("data=",data)
for row in data:
print(row) Output:
readcsv()
<class '_csv.reader'>
data= <_csv.reader object at 0x03168370>
['SN', 'Name', 'Contribution']
['1', 'Linus Torvalds', 'Linux Kernel']
['2', 'Tim Berners-Lee', 'World Wide Web']
['3', 'Guido van Rossum', 'Python Programming']
CSV Files with Custom Delimiters
By default, a comma is used as a delimiter in a CSV file. However, some CSV files can
use delimiters other than a comma. Few popular ones are | and \t.
Suppose we want to use | as a delimiter in the innovators.csv file of Example 1. To
write this file, we can pass an additional delimiter parameter to the csv.writer()
function.
Let's take an example.
Example 3: Write CSV File Having Pipe Delimiter
import csv
data_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, delimiter='|')
writer.writerows(data_list)
def readcsv():
with open('innovators.csv','rt')as f:
data = csv.reader(f) #reader function to generate a reader object
Output:
['SN|Name|Contribution']
['1|Linus Torvalds|Linux Kernel']
['2|Tim Berners-Lee|World Wide Web']
['3|Guido van Rossum|Python Programming']
CSV files with Quotes
Some CSV files have quotes around each or some of the entries.
Let's take quotes.csv as an example, with the following entries:
"SN";"Name";"Quotes"
1;"Buddha";"What we think we become"
2;"Mark Twain";"Never regret anything that made you smile"
3;"Oscar Wilde";"Be yourself everyone else is already taken"
Using csv.writer() by default will not add these quotes to the entries.
In order to add them, we will have to use another optional parameter called
quoting.
Let's take an example of how quoting can be used around the non-numeric values
and ; as delimiters.
import csv
row_list = [
["SN", "Name", "Quotes"],
[1, "Buddha", "What we think we become"],
[2, "Mark Twain", "Never regret anything that made you smile"],
[3, "Oscar Wilde", "Be yourself everyone else is already taken"]
]
with open('quotes.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC,
delimiter=';', quotechar='*')
writer.writerows(row_list)
def readcsv():
with open('quotes.csv','rt')as f:
data = csv.reader(f) #reader function to generate a reader object
for row in data:
print(row)
readcsv()
Output:
['*SN*;*Name*;*Quotes*']
['1;*Buddha*;*What we think we become*']
['2;*Mark Twain*;*Never regret anything that made you smile*']
['3;*Oscar Wilde*;*Be yourself everyone else is already taken*']
Anirudh of class 12 is writing a program to add records into
a CSV file and also to update the contents of the file.
He has written the following code. As a programmer,
help him to successfully execute the given task.
(b) Write a method in Python to read lines from a text file NOTES.TXT, and count
those lines, which are ending with ‘.’ or ‘,’. 2
(c) Create a binary file COMPANY.DAT having fields Code, FurnitType, Price , write a
method in Python to search and display the content in a pickled file COMPANY.DAT,
where FurnitType is matching with the value ‘HOME’. 3
def Display():
print ( CODE,":", FurnitType,":",PRICE)
CBSE 2018
4 (a) Write a statement in Python to open a text file STORY.TXT so that new contents can be
added at the end of it. 1
(b) Write a method in python to read lines from a text file INDIA.TXT, to find and display the 2
occurrence of the word “India”.
For example:
If the content of the file is
_______________________________________________________________________
“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
CBSE 2018
4 (c) Considering the following definition of class MULTIPLEX, write a method in
python to search and display all the content in a pickled file CINEMA.DAT, where
MTYPE is matching with the value ‘Comedy’. 3
class MULTIPLEX:
def __init__(self,mno,mname,mtype):
self.MNO = mno
self.MNAME = mname
self.MTYPE = mtype
def Show(self):
print (self.MNO:"*",self.MNAME,"$",self.MTYPE)
CBSE 2018 Compartment
4. (a) Write a statement in Python to open a text file NOTES.TXT so that new contents can be written in it. 1
(b) Write a method in python to read lines from a text file INDIA.TXT, to find and display the occurrence of the
word “INDIA” or “India”. 2
For example:
If the content of the file is
__________________________________________________________________
INDIA is a famous country all over the world.
Geographically, India is located to the
south of Asia continent. India is a high
population country and well protected
from all directions naturally.
India is a famous country for
its great cultural and traditional
values all across the world.
__________________________________________________________________
The output should be 4
CBSE 2018 Compartment
4. (c) Considering the following definition of class SHOPCOMPLEX, write a
method in python to search and display all the content in a pickled file
SHOP.DAT, where STYPE is matching with the value ‘Stationary’. 3
class SHOPCOMPLEX:
def __init__(self,sno,sname,stype):
self.SNO = sno
self.SNAME = sname
self.STYPE = stype
def Display(self):
print (self.SNO,",",self.SNAME,"#",self.STYPE)
CBSE 2019
4 (a) Write a statement in Python to open a text file WRITEUP.TXT so that new content can be written
in it. 1
Or
(a) Write a statement in Python to open a text file README.TXT so that existing content can be read
from it. 1
(b) Write a method/function ISTOUPCOUNT() in python to read contents from a text file WRITER.TXT,
to count and display the occurrence of the word “IS” or “TO” or “UP”. 2
For example:
If the content of the file is
_______________________________________________________________________
IT IS UP TO US TO TAKE CARE OF OUR SURROUNDING. IT IS NOT
POSSIBLE ONLY FOR THE GOVERNMENT TO TAKE RESPONSIBILITY
_______________________________________________________________________
The method/function should display
Count of IS TO and UP is 6
CBSE 2019
Or
(b) Write a method/function AEDISP() in python to read lines from a text file WRITER.TXT, and
display those lines, which are starting either with A or starting with E. 2
For example:
If the content of the file is
_______________________________________________________________________
A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD HEALTH.
WE SHOULD TAKE CARE OF OUR ENVIRONMENT.
EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD.
_______________________________________________________________________
The method should display
A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD HEALTH.
EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD.
CBSE 2019
(c) Considering the following definition of class STOCK, write a method /
function COSTLY() in python to search and display Name and Price from a
pickled file STOCK.DAT, where Price of the items are more than 1000. 3
class Stock:
def __init__(self,N,P):
self.Name=N
self.Price=P
def Show(self):
print (self.Name,"@",self.Price)
OR
CBSE 2019
(c) Considering the following definition of class DOCTORS, write a method
/function SPLDOCS() in python to search and display all the content from a
pickled file DOCS.DAT, where Specialisation of DOCTORS is “CARDIOLOGY”. 3
class DOCTORS:
def __init__(self,N,S):
self.Name=N
self.Specialisation=S
def Disp(self):
print (self.Name,"#",self.Specialisation)
CBSE 2019 Compartment
4 (a) Write a statement in Python to open a text file CONTENT.TXT so that new
contents can be written in it. 1
OR
(a) Write a statement in Python to open a text file REMARKS.TXT so that existing
content can be read from it. 1
(b) Write a method/function BIGWORDS() in Python to read contents from a
text file CODE.TXT, to count and display the occurrence of those words, which
are having 5 or more alphabets. 2
For example :
If the content of the file is ME AND MY FRIENDS
ENSURE SAFETY AND SECURITY OF EVERYONE
OR
CBSE 2019 Compartment
(b) Write a method/function BIGLINES() in Python to read lines from a text file
CONTENT.TXT, and display those lines, which are bigger than 20 characters. 2
For example :
If the content of the file is Stay positive and happy
Work hard and dont give up hope
Be open to criticism and keep learning
Surround yourself with happy, warm and genuine people
The method/function should display
Be open to criticism and keep learning
Surround yourself with happy, warm and genuine people
File Programs from NCERT Textbook
'''
Let us now write a program that accepts a string from the user and writes it to a text file. Thereafter, the
same program reads the text file and displays it on the screen.
Program 2-1 Writing and reading to a text file
''' Output:
fobject=open("testfile.txt","w") # creating a data file
sentence=input("Enter the contents to be written in the file: ") Enter the contents to be written in the file:
fobject.write(sentence) # Writing data to the file roll_numbers = [1, 2, 3, 4, 5, 6]
Now reading the contents of the file:
fobject.close() # Closing a file roll_numbers = [1, 2, 3, 4, 5, 6]
print("Now reading the contents of the file: ")
fobject=open("testfile.txt","r")
#looping over the file object to read the file
for str in fobject:
print(str)
fobject.close()
Application of seek() and tell()
Output:
Learning to move the file object
roll_numbers = [1, 2, 3, 4, 5, 6]
Application of seek() and tell() Initially, the position of the file object is: 33
print("Learning to move the file object") Now the file object is at the beginning of the file: 0
fileobject=open("testfile.txt","r+") We are moving to 6th byte position from the beginning of file
The position of the file object is at 5
str=fileobject.read() numbers = [1, 2, 3, 4, 5, 6]
print(str)
print("Initially, the position of the file object is: ",fileobject. tell())
fileobject.seek(0)
print("Now the file object is at the beginning of the file: ",fileobject.tell())
fileobject.seek(5)
print("We are moving to 6th byte position from the beginning of file")
print("The position of the file object is at", fileobject.tell())
str=fileobject.read()
print(str)
#Program 2-3 To create a text file and write data in it
# program to create a text file and add data
fileobject=open("practice.txt","w+")
while True:
data= input("Enter data to save in the text file: ")
fileobject.write(data)
fileobject.write('\n')
ans=input("Do you wish to enter more data?(y/n): ")
if ans=='n': break
fileobject.close() Output:
Enter data to save in the text file: Our Own High School
Do you wish to enter more data?(y/n): y
#Program 2-4 To display data from a text file Enter data to save in the text file: Dubai, U.A.E.
fileobject=open("practice.txt","r") Do you wish to enter more data?(y/n): n
Our Own High School
str = fileobject.read() Dubai, U.A.E.
print(str)
fileobject.close()
#Program 2-5 To perform reading and writing operation in a text file
fileobject=open("report.txt", "w+")
print ("WRITING DATA IN THE FILE") Output:
print() # to display a blank line
WRITING DATA IN THE FILE
while True:
line= input("Enter a sentence: ") Enter a sentence: Our Own
fileobject.write(line) The byte position : 9
fileobject.write('\n') Do you wish to enter more data? (y/n): y
Enter a sentence: High School
print("The byte position : ",fileobject.tell()) The byte position : 22
choice=input("Do you wish to enter more data? (y/n): ") Do you wish to enter more data? (y/n): y
if choice in ('n','N'): break Enter a sentence: Dubai
print("The byte position of file object : ",fileobject.tell()) The byte position : 29
Do you wish to enter more data? (y/n): n
fileobject.seek(0) #places file object at beginning of file The byte position of file object : 29
print()
print("READING DATA FROM THE FILE") READING DATA FROM THE FILE
str=fileobject.read() 26
Our Own
print(len(str))
High School
print(str) Dubai
#Program 2-6 Pickling data in Python
import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("mybinary.dat", "wb")
pickle.dump(listvalues,fileobject)
Output:
fileobject.close()
The data that were stored in file are:
[1, 'Geetika', 'F', 26]
#Program 2-7 Un-pickling data in Python
import pickle
print("The data that were stored in file are: ")
fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)
File Handling in Python
File Handling In Python - GeeksforGeeks