Data File Handling ProgramsMain
Data File Handling ProgramsMain
Read() function
1. The read() method returns the specified number of bytes from
the file. Default is -1 which means the whole file.
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.
Problems:-
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
"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( )
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)
O------0------o-------0-------O
Page 17 of 17