Computer Science (XII) Notes By Sumit Garg Sir
FILE HANDLING
A file in itself is a bunch of bytes stored on some storage device like hard disk, thumb drive etc.
TYPES OF FILE
TEXT FILE
1) A text file stores information in ASCII or unicode characters
2) each line of text is terminated, (delimited) with a special character known as EOL
BINARY FILES
1) A binary file is just a file that contains information in the same format in which the
information is held in memory i.e the file content that is returened to you is raw.
2) There is no delimiter for a line
3) No translation occurs in binary file
4) Binary files are faster and easier for a program to read and write than are text files.
5) Binary files are the best way to store program information.
CSV FILES
1) CSV is a simple file format used to store tabular data, such as a spreadsheet or database.
2) CSV stands for "comma-separated values“.
3) A comma-separated values file is a delimited text file that uses a comma to separate values.
4) Each line of the file is a data record. Each record consists of one or more fields, separated by
commas. The use of the comma as a field separator is the source of the name for this file format
Steps to process a FILE
OPEN THE FILE------> PROCESSING THE FILE ------ >CLOSE THE FILE
OPENING FILES
Using open Function
open() function is used to open a file
Syntax:
file variable/file handle=open(file_name,access mode)
Examples
Programming example description
F= open('abc.txt,'w') this statement opens abc.txt in write mode.file abc.txt will
exist in same folder as python file
1
Computer Science (XII) Notes By Sumit Garg Sir
F= open('D:\\Computer\\abc.txt’) change the location of file then we have to mention
complete file path with file name . don t forget to mention
double slash in file path
F= if you don’t want to use // then use r in front of file
open(r'D:\Computer\abc.txt,'w')
Note : if file mode is not mentioned in open function then default file mode i.e 'r' is used
2)Use of With Clause
Syntax:
with open(“file name”,access mode) as file object
example with open(“book.txt”,’r’) as f
NOTE: no need to close the file explicitly if we are using with clause
CLOSING FILES
close() : the close() method of a file object flushes any unwritten information and close the file
object after which no more writing can be done.
SYNTAX: fileobject.close()
FILE MODE
It defines how the file will be accessed
Text Binary Description Notes
File File
Mode Mod
e
‘r’ ‘rb’ Read only File must exist already ,otherwise python raises
I/O
error
‘w’ ‘wb’ Write only *If the file does not exist ,file is created.
*If the file exists, python will truncate existing data
and overwrite in tne file. So this mode must be
used with
caution.
‘a’ ‘ab’ append *File is in write only mode.
*if the file exists, the data in the file is retained and
new data being written will be appended to the end.
*if the file does not exist ,python will create a new file.
‘r+’ ‘r+b’ or Read and *File must exist otherwise error is raised.
‘rb+’ write *Both reading and writing operations can take place.
‘w+’ ‘w+b’ Write *File is created if doesn’t exist.
or and read *If the file exists, file is truncated(past data is lost).
‘wb+’ *Both reading and writing operations can take place.
‘a+’ ‘a+b’ Write *File is created if does not exist.
or and read *If file exists, files existing data is retained ; new
‘ab+’ data is appended.
*Both reading and writing operations can take place.
2
Computer Science (XII) Notes By Sumit Garg Sir
TEXT FILE HANDLING
Methods to read data from files
S.N Method Syntax Description
O.
1 Read() <filehandle>.read( [n] ) Reads at most n bytes
If no n is specified, reads the entire file.
Returns the read bytes in the form of a
string In [11]:file
1=open(“E:\\mydata\\info.txt”)
In [12]:readInfo=file1.read(15)
In [13]:print(readInfo)#prints firt 15 #characters
of file
In
[14]:type(readInfo)
Out[14]:str
2 Readline( ) <filehandle>.readline([n]) Reads a line of input ;if in is specified reads at most
n bytes.
Returns the read bytes in the form string ending
with in(line)character or returns a blank string if no
more bytes are left for reading in the file.
In [20]:file1 = open(“E:\\mydata\\info.txt”)
In [20]: readInfo =file1.readline()
In [22]:print (readInfo)
3 readlines() <filehandle>.readlines() Read all lines and returns them in a list
In [23]:file1 =open(“E:\\mydata\\info text”)
In [24]:readInfo =file1.readlines()
In [25]:print (readInfo)
In [26]:type (readInfo)
Out[26]:list
3
Computer Science (XII) Notes By Sumit Garg Sir
Writing data into files
S. NO Name Syntax Description
1 Write() <filehandle>.write(str1) Write string str1 to file referenced
by<filehandle>
2 Writelines() <filehandle>.writelines (L) Writes all strings in list L as lines to file
referenced by <filehandle>
RELATIVE AND ABSOLUTE PATH
1) the os module provides functions for working with files and directories ('os' stands for
operating system). os.getcwd returns the name of the current directory
import os
cwd=os.getcwd()
print(cwd)#cwd is current working directory
2) A string like cwd that identifies a file is called path. A relative path starts from the
current directory whereas an absolute path starts from the topmost directory in file
system.
examples
f=open(‘test.txt’,r) \\test.txt is the relative path
f=open’(E:\project\myfolder\data.txt’,r) E:\project\myfolder\data.txt is absolute
path
SETTING OFFSETS IN A FILE:
To access the data in random fashion then we use seek () and tell () Method.
tell (): It returns an integer that specifies the current position of the file object in the file.
fileobject.tell()
seek(): It is used to position the file object at a particular position in a file. fileobject.seek(offset [,
reference point]) where offset is the number of bytes by which the file object is to be moved and
reference point indicating the starting position of the file object. Values of reference point as 0-
beginning of the file, 1- current position of the file, 2- end of file.
4
Computer Science (XII) Notes By Sumit Garg Sir
BINARY FILES IN PYTHON:
A Binary file stores the information in the form of a stream of bytes. A binary file stores the data in
the same way as stored in the memory. In Binary file there is no delimiter for a line. The file contents
returned by a binary file is raw i.e. with no translation, thus Binary files are faster than text files. To
work with binary files, you need to open them using specific file modes:
To open a binary file follow this syntax:
file = open(, mode)
For example:
f = open(“one.dat”,”rb”)
Binary File Modes:
• rb: Read a binary file. The file pointer is placed at the beginning of the file. This is the
default mode for reading.
• rb+: Read and write a binary file. The file pointer is placed at the beginning of the file.
• wb: Write to a binary file. This mode will overwrite the file if it exists, or create a new file if
it doesn't.
• wb+: Write and read a binary file. This mode will overwrite the file if it exists, or create a
new file if it doesn't.
• ab: Append to a binary file. The file pointer is at the end of the file if it exists. If the file does
not exist, it creates a new file for writing.
• ab+: Append and read a binary file. The file pointer is at the end of the file if it exists. If the
file does not exist, it creates a new file for writing.
Closing a Binary File
Always close a file after you're done using it to ensure that all resources are properly released. Use
the close() method:
Differences Between Binary Files and Text Files
1. Nature of Data
Binary Files: Store data in binary format (0s and 1s). The data is not human-readable and can represent
various types of data, including images, audio, and executable code.
Text Files: Store data in plain text format. The data is human-readable and consists of characters
encoded in formats such as ASCII or Unicode.
2. Usage
Binary Files: Used for data that is not meant to be read directly by humans, such as media files,
compiled programs, and data serialization.
Text Files: Used for data that needs to be read and edited by humans, such as source code, configuration
files, and documents.
3. Encoding
Binary Files: No specific encoding scheme; the interpretation of bytes depends on the file
format. Text Files: Use character encoding schemes like ASCII, UTF-8, or UTF-16 to represent
text.
5
Computer Science (XII) Notes By Sumit Garg Sir
Python objects (list, dictionary etc) have a specific structure which must be maintained while
storing or accessing them. Python provides a special module called pickle module for this.
PICKLING refers to the process of converting the structure(list/dictionary) to a byte of stream before
writing it to a file. The process to converts any kind of python objects (list, dict etc.) into byte streams (0s
and 1s).
UNPICKLING is used to convert the byte stream back to the original structure while
reading the contents of the file.
pickle Module: -
Before reading or writing to a file, we have to import the pickle
module. Eg.
import pickle
pickle module has two main methods: dump() and load()
pickle.dump() – This method is used to write the object in the file which is opened in ‘wb’ or ‘ab’ i.e.
write
binary or append binary access mode respectively.
Syntax :
pickle.dump(<structure>,<FileObject>)
Here, Structure can be list or dictionary.
FileObject is the file handle of file in which we have to
write. # Simple program to write a list data into a binary
file import pickle
fo = open("binary_file1.dat","wb")
Laptop = ["Dell","HP","ACER"]
pickle.dump(Laptop,fo)
fo.close()
pickle.load() – This method is used to read data from a file and return back into the structure
(list/dictionary). Syntax :
<structure> = pickle.load(<FileObject>)
Structure can be any sequence in Python such as list, dictionary etc. FileObject is the file handle of file in
which we have to write.
# Program to read data from a binary file
fbin = open("binary_file1.dat","rb")
x=pickle.load(fbin)
print(x)
fbin.close()
# Simple program to write a dictionary data into a binary file
import pickle
f=open("my_bin1.bin","wb")
D1={3:'Maruti',2:'Honda',4:'Hundai',1:'BMW'}
pickle.dump(D1,f)
f.close()
6
Computer Science (XII) Notes By Sumit Garg Sir
f1=open("my_bin1.bin","rb")
D2=pickle.load(f1)
print(D2)
f.close()
#Write data to a Binary File:
import pickle
list =[ ] # empty list
while True:
roll = input("Enter student Roll No:")
sname=input("Enter student Name:")
student={"roll":roll,"name":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()
OUTPUT:
Enter student Roll No: 1201
Enter student Name: Anil
Want to add more
record(y/n): y Enter student
Roll No: 1202 Enter student
Name: Sunil
Want to add more record(y/n): n
Read data from a Binary File:
To read the data from a binary file, we have to use load() function
Example:
import pickle
file = open("student.dat", "rb")
list =pickle.load(file)
print(list)
file.close()
OUTPUT:
[{'roll':'1201','name':'Anil'},{'roll':'1202','name':'Sunil'}]
Update a record in Binary File:
def update():
name=input("Enter the name to be updated ")
newstu=[]
while True:
try:
stu=p.load(f)
for i in stu:
if i[1].lower()==name.lower():
rno=int(input("Enter the updated Roll number"))
s=[rno,name]
newstu.append(s)
else:
newstu.append(i)
except:
break
f.close()
f=open("student.dat","rb+")
7
Computer Science (XII) Notes By Sumit Garg Sir
update()
p.dump(newstu,f)
print(“Record updated”)
f.close()
OUTPUT:
Enter the name to be updated
Sunil Enter the updated Roll
number 1204 Record updated
Delete a record from binary file:
import pickle
def deletestudent():
roll=input('Enter roll number whose record you want to delete:')
list = pickle.load(fw)
found=0
lst= []
for x in list:
if roll not in x['roll']:
lst.append(x)
else:
found=1
fw=open(“student.dat”,”rb+”)
delestudent()
pickle.dump(lst,fw)
fw.close()
if found==1:
print(“Record Deleted”)
else:
print(“Record not found”)
OUTPUT:
Enter roll number whose record you want to
delete:1201 Record Deleted
8
Computer Science (XII) Notes By Sumit Garg Sir
CSV FILES
CSV stands for Comma Separated Values. It is a type of plain text file that uses specific
structure to arrange tabular data i.e. data stored in rows and columns such as a spreadsheet or
database.
CSV is like a text file, It is in human readable format and extensively used to store tabular data,
in a spreadsheet or database.
Each line of the csv file is a data record. Each record consists of one or more fields,
separated by commas. The separator character of CSV files is called a delimiter.
Default delimiter is (,). Other delimiters are tab(\t), colon (:), pipe(|), semicolon (;) characters.
READING FROM A CSV FILE
To read data from csv files, reader() method of csv module is used. csv.reader() returns a
reader object.
STEPS TO READ
1. import csv module
import csv
2. Open csv file in read mode.
f = open(“csv_demo.csv”,”r”)
3. Create the reader object.
demo_reader = csv.reader(f)
4. Fetch data through for loop, row by
row. for x in demo_reader:
print(x)
5. Close the file
f.close()
WRITING IN TO CSV FILES:
To write data into csv files, writer() function of csv module is used.
csv.writer(): This function returns a writer object which writes data into writer object.
Significance of writer object
The csv.writer() returns a writer object that converts the data into a delimited string. The string
can be later converted into csv files using the writerow() or writerows() method.
Syntax:
<writer_object>.writerow() : Writes one row of data in to the writer object.
<writer_object>.writerows(): Writes multiple rows into the writer object.
# Program to write data into a CSV File and to read data stored in csv file
import csv
f=open("mycsv.csv","w",newline='')
w=csv.writer(f)
lst=["RNO","NAME","MARKS"]
w.writerow(lst)
n=int(input('Enter how many students record you want to add'))
for x in range(n):
r=int(input('Enter rno'))
9
Computer Science (XII) Notes By Sumit Garg Sir
n=input('Enter name')
m=int(input('Enter
marks')) lst2=[r,n,m]
w.writerow(lst2)
f.close()
10
Computer Science (XII) Notes By Sumit Garg Sir
f=open("mycsv.csv","r")
rec=csv.reader(f)
for i in rec:
print(i)
f.close()
# Program to write Employee Name, EmpID and Dept for some employees in a csv file then
display records of all the employees.
import csv
f=open("emp.csv","w",newline='')
emp_writer = csv.writer(f)
emp_writer.writerow(["EmpName","EmpID","Dept"])
emp_rec = []
while True:
print("Enter Employee details: ")
empname = input("EmpName : ")
eid = int(input("EmpID : "))
dept = input("Department : ")
emp_rec.append([empname,eid,dept])
ch = input("Do you want to continue ??
(Y?N)") if ch == "N" or ch =="n":
break
emp_writer.writerows(emp_rec)
f.close()
f=open("emp.csv","r")
rec=csv.reader(f)
for i in rec:
print(i)
f.close()
11