0% found this document useful (0 votes)
1 views17 pages

Data File Handling ProgramsMain

The document provides an overview of file handling in Python, detailing various functions such as read(), readline(), and readlines() for reading file contents. It also explains different file modes for opening files, including text and binary modes, and includes several programming exercises for counting characters, words, and lines in files. Additionally, it covers the use of the pickle module for serializing Python objects into binary files.

Uploaded by

iakshatmaurya666
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)
1 views17 pages

Data File Handling ProgramsMain

The document provides an overview of file handling in Python, detailing various functions such as read(), readline(), and readlines() for reading file contents. It also explains different file modes for opening files, including text and binary modes, and includes several programming exercises for counting characters, words, and lines in files. Additionally, it covers the use of the pickle module for serializing Python objects into binary files.

Uploaded by

iakshatmaurya666
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/ 17

Data File Handling Programs (XII CS)

Read() function
1. The read() method returns the specified number of bytes from
the file. Default is -1 which means the whole file.

Read(n) will return n bytes(n characters of the string) from


the file. If the contents of
hello.txt is

practice makes a man perfect


welcome to kendriya vidyalaya.
Then read(10) will return -----practice m

2. Readline():- It reads first line of the file. If you open the file in
normal read mode, readline() will return you the string. If you
open the file in binary mode, readline() will return you binary
object.

Readline(n):- It will read only the first n bytes of the file i.e n
characters of the string

3.Readlines():-f.readlines(n)
It returns list of lines and append newline character i.e
“\n” at the end of each line. By default n is -1 which returns
the whole file.
Ex:-[“ practice makes a man perfect\n”,” welcome to kendriya
vidyalaya.\n”].

Page 1 of 17
Readlines(n):-for n<= (no. of characters of first line+1) where +1 is for “\n”,
readlines(n) will return first line, from next integer value it will return upto second
line till n<=(no. of characters of second line+1) .
Ex:-If there is a file hello2.txt having contents as:-
welcome #7 characters + 1 for \n = 8 characters
to #2 characters + 1 for \n = 3 characters
Adampur #7 characters + 1 for \n = 8 characters
Then readlines will return------[“ welcome\n”,” to\n”,” Adampur\n”]
Now, readlines(n) will return ['welcome \n'] for n=1 to 8
readlines(n) will return ['welcome \n',’to\n’] for n=1 to 11(8+3)
readlines(n) will return [‘ welcome\n’,’to\n’,’Adampur\n’] for n>11.

Modes of File opening

Text file Binary Description


mode File Mode
‘r’ ‘rb’ Read - Default value. Opens a file for reading, error if the file does
not exist.
‘w’ ‘wb’ Write - Opens a file for writing, creates the file if it does not exist
‘a’ ‘ab’ Append - Opens a file for appending(writing only), creates the file
if it does not exist.
‘r+’ ‘rb+’ Read and Write-File must exist, otherwise error is raised.
‘w+’ ‘wb+’ Read and Write-File is created if does not exist.
‘a+’ ‘ab+’ Read and write-Append new data. Creates the file if it does not exist.
‘x’ ‘xb’ Create - Creates the specified file, returns an error if the file exists

Problems:-

Contents of Hello.txt file practice makes a man perfect


welcome to kendriya vidyalaya.
A. Find output (if the initial contents of the file story.txt is
“Welcome”).
fout=open("story.txt","a")
fout.write("Python")
print(fout.tell( ))
Page 2 of 17
fout.close( )
1. WAP in Python to count no. of characters within a file (Including
White spaces)
f=open("hello.txt","r")
data=f.read()
count=0
for i in data:
count=count+1
print(count)
f.close()
1A. WAP in Python to count n no. of characters within a file.
f=open("hello.txt","r")
data=f.read(10) ’’’reads 10 characters of the file from the current cursor position.
print(len(data))
2. WAP in Python to count no. of characters within a file (Excluding
White spaces)
f=open("hello.txt","r")
data=f.read()
x=data.split() #x is list of words ex:-
[“practice”,”makes”,”a”,”man”,”perfect”……..]
count=0
for i in x:
count=count+len(i)
print(count)
3. WAP to count no. of words within a file.
f=open("hello.txt","r")
count=0
data=f.read()
x=data.split()
for i in x:
count=count+1
print(count)
4. WAP to count no. of lines within a file.
Page 3 of 17
f=open("hello.txt","r")
data=f.readlines() '''returns returns list of lines i.e
each line of char's as 1 element.'''
print(len(data)) '''It gives no. of elements in the list.2
lines..2 elts.’’’
OR
data=f.readlines()
count=0
for i in data: ‘’’It counts line by line.
count+=1
print(count)
4A. WAP to count no. of characters in the first line of the file hello.txt.
f=open("hello.txt","r")
count=0
data=f.readlines() # [“ practice makes a man perfect\n”,” welcome
to kendriya vidyalaya.\n”]
x=data[0] #reads first elt. of list i.e first line of file hello.txt
for i in x: #for each character in first line
count+=1
print(count)
4B. WAP to count no. of words in the first line of the file hello.txt.
f=open("hello.txt","r")
count=0
data=f.readlines()
x=data[0].split() #reads first elt. of list i.e first line of file
hello.txt
for i in x: #for each character in first line
count+=1
print(count)
5. WAP to count no. of vowels in a file
count=0
f=open("hello.txt","r")
while(True):
Page 4 of 17
ch=f.read(1)
if ch in ["a","e","i","o","u","A","E","I","O","U"]:
count+=1
elif ch=="":
break
f.close()
print("total no. of vowels ",count)
6. To count No. of vowels in a file
count=0
f=open("hello.txt","r")
ch=f.read()
for i in ch:
if i in ["a","e","i","o","u","A","E","I","O","U"]:
count+=1
f.close()
print("total no. of vowels ",count)
7. Count the no. of words starting with vowels.
f=open("hello.txt","r")
count=0
data=f.read()
wrd=data.split() #wrd is list of words
lst=["a","e","i","o","u","A","E","I","O","U"]
for i in wrd:
if i[0] in lst:
count+=1
print("words are:",i)
print("no. of words starting with vowels:",count)
8. Count the no. of lines starting with consonants.
f=open("hello.txt","r")
count=0
data=f.readlines()
lst=["a","e","i","o","u"]
for i in data:
Page 5 of 17
if i[0] not in lst:
count+=1
print(i)
print("no. of lines starting with consonant",count)
9. WAP to print those line from a file having p character in it.
f=open("hello.txt","r")
data=f.readlines()
for i in data: #Traversing list of lines.for i=0 means first line
for j in i: #Traversing each character of a line(for i=0, means line 1)
if j=="p" or j==”P":
print(i)
break '''checks for only first occurence of p otherwise
prints same line for each occurence of p.'''
f.close()
10. WAP to count the no. of ‘is’ word present within a file.
fin=open("D:\\python programs\\Book.txt",'r')
str=fin.read( )
L=str.split( )
count=0
for i in L: #Traversing list of words.for i=0 means first word
if i=='is':
count=count+1
print(count)
fin.close( )
10 Write a method in python to write multiple lines of text contents
A into a text file myfile.txt
def write1():
f = open("myfile.txt","w")
while True:
line = input("Enter line")
f.write(line)
choice = input("Are there more lines")
if choice = = "N" or choice= =’n’:
break
Page 6 of 17
f.close()
write1()
11. WAP to write those lines having ‘p’ from hello.txt to another file
hi.txt.
f=open("hello.txt","r")
f1=open("hi.txt","w")
data=f.readlines()
for i in data: #Traversing list of lines
for j in i: #Traversing each character of a line
if j=="p":
print(i)
f1.write(i)
print("data written")
break #ensures writing for only first occurence of p.
f.close()
f1.close()
12. Write a program to take the details of book from the user and write
the record in text file.
fout=open("D:\\python programs\\Book.txt",'w')
n=int(input("How many records you want to write in a file ? :"))
for i in range(n):
print("Enter details of record :", i+1)
title=input("Enter the title of book : ")
price=float(input("Enter price of the book: "))
record=title+" , "+str(price)+'\n'

fout.write(record)
fout.close( )
13. Copying lines to another file not starting wid lower case.
f=open("hello.txt","r")
f1=open("hi.txt","w")
data=f.readlines()
for i in data: #Traversing list of lines.
if i[0].islower(): #Accessing first character of a line.
Page 7 of 17
pass #Empty statement
else:
print(i)
f1.write(i)
print("data written successfully")
f.close()
f1.close()
14. Writing those no’s from a list which are divisible by 3 but not
divisible by 5 to a file hi.txt .
f=open("hi.txt","w")
lst=[1,4,3,6,9,15,21,30]
for i in range (len(lst)):
if lst[i]%3==0 and lst[i]%5!=0:
print(lst[i])
f.write(str(lst[i]))
f.write("\n")
print("data written successfully")
f.close()
15. Open the file "Book.txt" and append content to the file:
fout= open("Book.txt", "a")
fout.write("Welcome to the world of programmers")
fout.close()
Text Files Vs Binary Files

Text File Binary File


Its Bits represent character. Its Bits represent a custom data.
Less prone to get corrupt as Can easily get corrupted, corrupt
change reflects as soon as on even single bit change.
made and can be undone.
Store only plain text in a file.Can store different types of data
(audio, text,image) in a single
file.
Widely used file format and can Developed for an application and
be opened in any text editor. can be opened in that
Page 8 of 17
application only.
Mostly .txt,.rtf are used as Can have any application defined
extensions to text files. extension.
16. Open the file "Book.txt" and write contents to a file in binary mode.
fout= open("Book.txt", "wb")
fout.write("Welcome to the world of programmers")
fout.close()

#This code will generate error :- TypeError: a bytes-like object is


required, not 'str'
Correct code:-prefix writing string with b.

fout= open("Book.txt", "wb")


fout.write(b"Welcome to the world of programmers")
fout.close()
OR
f1=open("storyEncd.dat","wb") # open file in write and binary mode
Norml_str= "Once upon a time"
encoded_str= Norml_str.encode("ASCII") # encoding normal text
f1.write(encoded_str) # Write data in file
f1.close()
17. Delete the file "Book.txt":
import os #operating system module.
if os.path.exists("hello11.txt"):
os.remove("hello11.txt")
print("File deleted successfully")
else:
print("The file does not exist")

"Binary" files are any files where the format isn't made up of readable
characters. Binary files can range from image files like JPEGs or GIFs,
audio files like MP3s etc.
Moreover Binary files also used to write Python objects (Lists, Dictionaries
etc.) to the file directly. For it we uses pickle module
Page 9 of 17
i.e Pickling is the process of converting a Python object(list,
tuple, dictionary etc.) into a byte stream to store it in a
file/database or transport data over the network (writing to a
file) and “unpickling” is the inverse operation, whereby a
byte stream (from a binary file or bytes-like object) is
converted back into an object hierarchy(Reading into the
file).
So, you can use pickle module with binary files only.
Pickle uses dump()method to write data in files(pickling)
whereas it uses load() method to retrieve data from binary
files(unpickling).
1.Pickle is specific to Python i.e it is not cross language
compatible.
2.Pickle is also version specific.
3.The pickle module is not secure against erroneous or
maliciously constructed data i.e it is unsafe.
Note:- For using pickle functions you need to import pickle module as import
pickle
1 WAP to write Python objects in Binary file using pickle dump()method.
8.
import pickle
number_of_data = int(input('Enter the number of data : '))
data = []
for i in range(number_of_data):
raw = input('Enter data '+str(i+1)+' : ') str(1+1)=str(2)=’2’
data.append(raw)

Page 10 of 17
# open a file, where you want to store the data
file = open('important', 'wb')
pickle.dump(data, file)
file.close()
OR
import pickle
list =[ ] # empty list
while True:
roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
student = {"rno":roll,"nm":sname} # create a dictionary
list.append(student) # add the dictionary as an element in the list
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break
file = open("student.dat","wb") # open file in binary and write mode
pickle.dump(list, file)
file.close( )
1 WAP to read Python objects in Binary file using pickle load()method.
9.
import pickle
file = open("important", "rb")
list = pickle.load(file)
print(list)
file.close( )
OUTPUT:-
['kamal', '81']
OR
import pickle
file = open('important', 'rb')
data = pickle.load(file)
file.close()
print('Showing the pickled data:')
cnt = 0
for item in data: #Traversing list elements.
print('The data ', cnt+1, ' is : ', item)
cnt += 1

OUTPUT:-
Page 11 of 17
Showing the pickled data:
The data 1 is : kamal
The data 2 is : 81
2 Update a record in Binary File:
0.
[{‘roll’:12,’name’:’kamal’} , {‘roll’:1,’name’:’Isha’} ,
{‘roll’:14,’name’:’Rajender’} ]
import pickle
rno = input('Enter roll number whose name you want to
update in binary file :')
file = open("student.dat", "rb+")`
list = pickle.load(file) #LIST OF DICTIONARIES [{“roll”:2,”name”:”kamal”},{ } ]
found = 0
lstNew = [ ]
for x in list: #reading each dictionary elt. one by one
if rno in x['roll']:
found = 1
x['name'] = input('Enter new name: ')
lstNew.append(x) #Writing all dict. along with updated ones to new
list
if found == 1:
file.seek(0) #beginning cursor at the beginning of
file.
pickle.dump(lstNew, file) #overwriting new list to the file.
print("Record Updated")
else:
print('roll number does not exist')
file.close( )
2 Deleting record from a Binary file.
1.
[{‘roll’:12,’name’:’kamal’},{‘roll’:1,’name’:’Isha’},
{‘roll’:14,’name’:’Rajender’} ]
import pickle
Page 12 of 17
roll = input('Enter roll number whose record you want to delete:')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
lstNew = []
for x in list: #Traversing list of dictionary.
if roll not in x['roll']: #searching for value of roll key from
dictionary.
lstNew.append(x) #Created new list having elts other then specified for deletion.
else:
found = 1 #i.e when we found the rollno in file i.e entered for deletion.
if found == 1:
file.seek(0) #Bringing the cursor to initial position.
pickle.dump(lstNew, file) #Overwriting file contents with new list
contents
print("Record Deleted ")
else:
print('Roll Number does not exist')
file.close( )

2 Search a record in a binary file:


2.
[{‘roll’:12,’name’:’kamal’} , {‘roll’:1,’name’:’Isha’} ,
{‘roll’:14,’name’:’Rajender’} ]
import pickle
roll = input('Enter roll number that you want to
search in binary file :')
file = open("student.dat", "rb")
list = pickle.load(file) #list of dictionaries
for x in list: #checking dictionary elt. one by
one.
Page 13 of 17
if roll in x['roll']:
print("Name of student is:", x['name'])
break
else:
print("Record not found")
file.close( )

CSV FILES HANDLING IN PYTHON


Reading contents from a CSV file:- csv.reader(file
object)
Steps:-
1) CSV file is opened as a text file using open()
method,which returns a file object.(Ex:-
file=open(“student.csv”,’r’).
This file object is passed to the reader() function to
access the CSV file.
[Ex:- rdr= csv.reader(file) ]
2)This rdr object is iterable and gives access to each
line/record of CSV file as a list of fields.
For Ex:- if the contents of CSV file is then

rdr object when operated using next() or ['Name', ' Marks ']
using for loop will return 3 lists having all ['kamal', ' 85']
column/field values. ['pawan', '98']
23. Program to read contents of csv file and print records:-
Page 14 of 17
import csv
count=0
f=open("test.csv",'r')
csvRdr1=csv.reader(f)
for row in csvRdr1: #using for loop to read each record
print(row)
count=count+1
print("Total no. of records in the csv file are:-",count)
f.close()
24. Program to search records in a CSV file
import csv
f=open("test.csv",'r')
csvRdr1=csv.reader(f)
name=input("Enter the name of student to be searched")
for row in csvRdr1: #using for loop to read each record
if(row[0]==name):
print(row)
f.close()
With open function:-
1) No need to explicitly close the file object.it does automatically.
2) We can open multiple files using it.
Ex:-
with open(in_filename) as in_file,
open(out_filename, 'w') as out_file:
import csv
count=0
with open("test.csv",'r') as f:
csvRdr1=csv.reader(f)
for row in csvRdr1: #using for loop to read each record
print(row)
count=count+1
print("Total no. of records in the csv file are:-",count)

Page 15 of 17
Writing contents to a CSV file:- csv.writer(file object)
Steps:-
1)Contains a list of items as column/field names or headings.
Ex:- fields=['Name','Class','Year','Percent']
2)Also create list of lists for writing as rows of the table. Each
list within main list will act as 1 row.
Ex:- rows=[ ['kamal','XII','2013','92'],['Pawan','XI','2010','82']
]
3)Open the file in ‘w’ mode for writing the contents.
Ex:- with open(filename,'w',newline='') as f:
We have taken newline=’’ because when we use writerow()
function, it automatically places cursor to the next line. By
default newline=’\n’, So if we don’t use newline='' then it
will insert a blank line in between every record. One \n by
writerow and other by newline=’\n’.
4)Create a csv writer object
Ex:- csv_w=csv.writer(f,delimiter=',')
5) Writing contents to the file using writerow function. Ex:-
csv_w.writerow(fields) OR for i in rows:
csv_w.writerow(i)

25. WAP in Python to write contents to a CSV file


import csv
fields=['Name','Class','Year','Percent']
rows=[['kamal','XII','2013','92'],['Pawan','XI','2010','82']]
#nested list
Page 16 of 17
filename='marksdetails.csv'
with open(filename,'w',newline='') as f:
csv_w=csv.writer(f,delimiter=',')
csv_w.writerow(fields)
for i in rows:
csv_w.writerow(i)
print("File Created")

O------0------o-------0-------O

Page 17 of 17

You might also like