Chapter 5 (File Handling) | PDF | Comma Separated Values | Text File
0% found this document useful (0 votes)
28 views

Chapter 5 (File Handling)

Uploaded by

paxecam470
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Chapter 5 (File Handling)

Uploaded by

paxecam470
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Chapter – 5 (File Handling)

Data Files – The data files are the files that store data for later use. The data files can be stored in two ways.
1. Text Files – A text file stores information in ASCII or Unicode characters. In text file some internal translation
takes place. Execution is slow in text files.
2. Binary Files – A binary file contains information in the same format in which the information held in
memory. No translation occurs in binary files. Execution is fast in binary files.
Opening – We can open a file by open( ) function.
Syntax – <file_objectname> = open(<filename>)
<file_objectname> = open(<filename>, <mode>)
Example – myfile = open (“student.txt”) (default mode is read mode)
myfile = open (“student.txt”, “r”) (“r” denotes the read mode)
myfile = open(“e:\\main\\student.txt”, ”w”)
We can also take the full path of the file. In the above example // is used in place of / because /
represents the escape sequence. If we want to write with single slash (/), we may write in raw string
as:
myfile = open(r “e:\new\temp.txt”, ”r”)
File object – File objects (also called file-handle) are used to read and write data to a file on disk. A file object is a
reference to a file on disk. It opens and makes it available for a number of different tasks.
File access Modes – python used following modes:
Text file Mode Binary file Mode Description
‘r’ ‘rb’ Read only
‘w’ ‘wb’ Write only
‘a’ ‘ab’ Append
‘r+’ ‘r+b’ or ’rb+’ Read and write
‘w+’ ‘w+b’ or ‘wb+’ Write and read
‘a+’ ‘a+b’ or ‘ab+’ Write and read
Closing files – An open file is closed by calling the close ( ) method of its file object. A close ( ) function breaks the
link of file object and the file on the disk. After close ( ), no tasks can be performed on that file through the file object
(or file handle).
Syntax – <filehandle>.close ( )
Example – myfile.close ( )
Reading and writing files –
Reading from files – Python provides mainly three types of read functions to read from a data file.
1. read ( ) – Read at most n bytes. If no n is specified, reads the entire file.
Syntax – <filehandle>.read ([n])
Example – f=open("student.txt","r")
value=f.read(10)
print(value)
2. readline ( ) – It reads a line at a time.
Syntax – <filehandle>.readline([n])
Example – f=open("student.txt","r")
value=f.readline( )
print(value)
value=f.readline( )
print(value)
3. readlines ( ) – It reads all lines and returns them in a list.
Syntax – <filehandle>.readlines( )
Example – f=open("student.txt","r")
value=f.readlines( )
print(value)
Code Snippet 1: Reading a file’s first 30 bytes and printing it.
f=open("student.txt","r")
value=f.read(30)
print(value)
f.close()

Code Snippet 2: Reading n bytes and then reading some more bytes from the last position read.
f=open("student.txt","r")
value=f.read(20)
print(value)
value2=f.read(30)
print(value2)
f.close()

Code Snippet 3: Reading a file’s entire content.


f=open("student.txt","r")
value=f.read( )
print(value)
f.close()

Code Snippet 4: Reading a file’s first three lines – line by line.


f=open("student.txt","r")
value=f.readline()
print(value)
value2=f.readline()
print(value2)
value3=f.readline()
print(value3)
f.close()

Code Snippet 5: Reading a complete file – line by line.


f=open("student.txt","r")
value=" "
while value:
value=f.readline()
print(value)
f.close()

Code Snippet 6: Displaying the size of a file after removing EOL characters, leading and trailing white spaces and
blank lines.
f=open("student.txt","r")
str1=" "
size=0
tsize=0
while str1:
str1=f.readline()
tsize=tsize+len(str1)
size=size+len(str1.strip())
print("Size of file after removing all EOL & blanks",size)
print("Total size of file",tsize)
f.close()

Code Snippet 7: Reading a complete file – in a list.


f=open("student.txt","r")
s=f.readlines()
print(s)
f.close()
Writing onto files – Python provides mainly two types of write functions to write data to a file.
1. write ( ) – Writes a string value to a file.
Syntax – <filehandle>.write(str1)
2. writelines ( ) – Writes a list value to a file.
Syntax – <filehandle>.writelines(L)

Code Snippet 8: Create a file to hold some data.


f=open("student1.txt","w")
for i in range(5):
name=input("Enter the name of students:")
f.write(name)
f.close()

Code Snippet9: Create a file to hold some data, separated as lines.


f=open("student1.txt","w")
for i in range(5):
name=input("Enter the name of students:")
f.write(name)
f.write('\n')
f.close()

Code Snippet10: Creating a file with some names separated by newline characters without using write ( ) function.
f=open("student1.txt","w")
List1=[]
for i in range(5):
name=input("Enter the name of students:")
List1.append(name+'\n')
f.writelines(List1)
f.close()

Example 5.1: Write a program to get roll numbers, names and marks of the students of a class (get from user) and
store these details in a file called “marks.det”.
size=int(input("How many students are there in class:"))
f=open("marks.det","w")
for i in range(size):
roll=int(input("Enter the roll no:"))
name=input("Enter the name:")
marks=float(input("Enter the marks:"))
rec=str(roll)+","+name+","+str(marks)+"\n"
f.write(rec)
f.close()

Appending a file – When you open a file in “w” or wire mode, Python overwrites an existing file or creates a non-
existing file. That means, for an existing file with the same name, the earlier data gets lost. If you want to write into
the file while retaining the old data, then you should open the file in “a” or append mode. A file opened in append
mode retains its previous data while allowing you to add newer data into.

Example 5.2: Write a program to add two more students’ details to the file created in program 5.1.
f=open("marks.det","a")
for i in range(2):
roll=int(input("Enter the roll no:"))
name=input("Enter the name:")
marks=float(input("Enter the marks:"))
rec=str(roll)+","+name+","+str(marks)+"\n"
f.write(rec)
f.close()
Example 5.3: Write a program to display the contents of file “marks.det” created through program 5.1 and 5.2.
f=open("marks.det","r")
str1=" "
while str1:
str1=f.read()
print(str1)
f.close()
The flush ( ) function – The flush ( ) function forces the writing of data on disc still pending in output buffer.
Syntax – <fileobject>.flush ( )
Example – f=open("student1.txt","w")
name=input("Enter the name of students:")
f.write(name)
f.flush()
f.close()
Standard input, output and error streams –
1. Standard input device (stdin) – Reads from the keyboard.
2. Standard output device (stdout) – Prints to the display and can be redirected as standard input.
3. Standard error device (stderr) – Same as stdout but normally only for errors, displayed in red color
These standard devices are implemented as files called standard streams.
sys module is to be imported to use these streams.
1. sys.stdin.read ( )
2. sys.stdout.write ( )
3. sys.stderr.write ( )
Example –
import sys
f=open("student.txt")
line1=f.readline()
line2=f.readline()
sys.stdout.write(line1)
sys.stdout.write(line2)
sys.stderr.write("No errors occurred\n")
Path – The full name of a file or directory or folder consists of path. Path is a sequence of directory name which give
you the hierarchy to access a particular directory or file name.
Absolute and Relative path –
Directory Structure

Absolute Path – The absolute paths are from the topmost level of directory structure.
Example –
E:\Personal Docs
E:\Personal Docs\Imp Files\Project.py
E:\Personal Docs\Project.py
E:\Movies\Bollywood\2.mp4
Relative Path – The relative paths are relative to the current working directory, denoted as a dot (.), while its
parent directory is denoted with two dots (..)
Example – So, with Imp Files is current working folder, path name of File1.docx is .\File1.docx which means under
current working folder.
CSV Files – CSV stands for Comma Separated Values. CSV is just like a text file, in a human readable format which is
extensively used to store tabular data, in a spreadsheet or database. The separator character of CSV files is called a
delimiter. Default delimiter is comma (,). Other delimiters are tab (‘\t’), colon (:), pipe (|), semicolon (;) characters.
Advantages of CSV File –
1. Universal Use
2. Easy to understand
3. Quick to create
4. Large amount can store
Python csv module – csv module provides two types of objects:
1. reader – To read from CSV files.
2. writer – To write into the CSV files.
To import csv module in our program, write the following statement:
import csv
Opening/ Closing csv files –
1. Open a CSV file –
f=open(“student.csv”, “w”)
or
f=open(“student.csv”, “r”)
2. Close a CSV file –
f.close( )
Role of Argument newline in opening of csv files – Newline argument specifies how would Python handle new
line character while working with CSV files, on different operating system. Different operating systems store EOL
character differently. Addition optional argument as newline = ' ' with file open ( ) will ensure that no translation of
End of Line (EOL) character takes place.
Example – f = open ("details.csv", "w", newline=' ')
Writing in CSV files – We can use following functions to write in a CSV file:
1. csv.writer ( ) – Returns a writer object which writes data into CSV files.
2. <writerobject>.writerow ( ) – Writes one tow of data on to the writer object.
Example –
import csv
def create( ):
f=open("details.csv", "w", newline=' ')
f1=csv.writer(f)
f1.writerow (['Roll','Name','Total Marks'])
while True:
roll=int(input("Enter Roll no:"))
name=input("Enter name:")
total=int(input("Enter total Marks:"))
record=[roll,name,total]
f1.writerow (record)
ch=int(input("1.More record\n2.Exit\nEnter your choice:"))
if ch==2:
break;
3. <writerobject>.writerows ( ) – Writes multiple rows on to the writer object.
Example –
import csv
def create( ):
f=open("details.csv", "w", newline=' ')
f1=csv.writer(f)
f1.writerow (['Roll','Name','Total Marks'])
rec = [ ]
while True:
r=int (input ("Enter Roll no :"))
n=input ("Enter name :")
t=in t(input("Enter total Marks:"))
record = [r, n, t]
rec.append (record)
ch=int(input("1.More record\n2.Exit\nEnter your choice:"))
if ch==2:
break;
f1.writerows(rec)
Role of writer object – the csv.writer ( ) functions returns a writer object that converts the user’s data into a
delimited string. This string can later be used to write into CSV files using writerow ( ) function or writerows ( )
function.
Reading from CSV files – To read data from a CSV file, reader function of csv module is used.
1. csv.reader ( ) – Returns a reader object. It loads the data from CSV file into an iterable after parsing
delimited data.
Example –
def display( ):
f=open("details.csv", "r", newline='\r\n')
f1=csv.reader(f)
for i in f1:
print(i)
Question: Write a program to write and read data from CSV file consisting Item No, Item Name, Quantity and Price.
Write a function to search for a particular item using Item Code.
import csv
def create( ):
f=open ("item.csv", "w", newline=' ')
f1=csv.writer (f)
f1.writerow (['Item No', 'Item Name', 'Quantity', 'Price'])
rec = [ ]
while True:
no=int (input("Enter Item No:"))
name=input ("Enter Item Name:")
qty=int (input ("Enter Quantity:"))
price=float(input("Enter Price:"))
record=[no, name, qty, price]
rec.append (record)
ch=int(input("1.More record\n2.Exit\nEnter your choice:"))
if ch==2:
break;
f1.writerows (rec)
def display( ):
f=open("item.csv", "r", newline='\r\n')
f1=csv.reader (f)
for i in f1:
print (i)
def search( ):
f=open ("item.csv", "r", newline='\r\n')
s=input ("Enter the Item No for search")
print("Displaying record")
f1=csv.reader (f)
next (f1)
for i in f1:
if i[0]==s:
print (i)

create( )
display( )
search( )
Binary Files – Most of the files that we see in our computer system are called binary files.
1. We can open some binary files in the normal text editor but we cannot read the content present inside the
file.
2. That’s because all the binary files will be encoded in the binary format, which can be understood only by a
computer or a machine.
3. In binary files, there is no delimiter to end a line.
4. Since they are directly in the form of binary, hence there is no need to translate them.
5. Binary files are easy and fast in working.
Example –
 Image files: .png, .gif, .jpg, .bmp etc.
 Video files: .mp4, .3gp, .mkv, .avi etc.
 Audio files: .mp3, .wav, .mka, .aac, etc.
 Archive files: .zip, .rar, .iso, .7z etc.
 Executable files: .exe, .dll, .class etc.
Pickling and Unpickling –
Pickling – Pickling refer to the process of converting the structure (such as list or dictionary) to a byte stream before
writing to the file.

Structure (List
Pickling Byte
or Dictionary)
Stream

Unpickling – Unpickling refer to the process of converting the byte steam back to the original structure.

Byte Structure (List


Pickling or Dictionary)
Stream

Pickle Module – Pickle module is used to store any kind of object in file as it allows us to store python objects with
their structure. So for storing data in binary format, we will use pickle module. First we need to import the module. It
provides two main methods for the purpose, dump and load.
Example – import pickle
1. Pickle.dump( ) function – This function is used to write the object in a file.
Syntax – pickle.dump(<Structure>, FileObject)
Note: Structure can be any sequence of Python. It can be either list or dictionary.
2. Pickle.load( ) function – This function is used to read data from a file.
Syntax – structure = pickle.load (FileObject)
Note: Structure can be any sequence of Python. It can be either list or dictionary.
Example – import pickle
def write():
f=open("student.dat",'wb')
List=['comp','Math','English','Physics','Chemistry']
dic={'comp':100,'Math':98,'English':74,'Physics':40,'Chemistry':80}
pickle.dump(List,f)
pickle.dump(dic,f)
f.close()
def read():
f=open("student.dat",'rb')
lst=pickle.load(f)
d=pickle.load(f)
print(lst)
print(d)
f.close()
write()
read()
Example – Write a program to write and read multiple data from a binary file.
import pickle
def write():
f=open("student.dat",'wb')
record=[]
while True:
rno=int(input("Enter roll no:"))
name=input("Enter Name:")
marks=int(input("Enter Marks:"))
data=[rno,name,marks]
record.append(data)
ch=input("Dou you want to enter more records?(y/n)")
if ch=='n':
break
pickle.dump(record,f)
def simpleread():
f=open("student.dat",'rb')
s=pickle.load(f)
print(s)
write()
def read():
f=open("student.dat",'rb')
s=pickle.load(f)
for i in s:
rno=i[0]
name=i[1]
marks=i[2]
print(rno,name,marks)
simpleread()
read()
Random aces in File Handling –
1. seek()
2. tell()
1. seek() function – seek() function is used to change the position of the file handle (file pointer) to a given
specific position. File pointer is like a cursor, which defines from where the data has to be read or writer in
the file.
Syntax – f.seek(offset, from_what)
Where f is file pointer.
“From_what” – The reference point is defined by the “from-what” argument. It have any of three values:
1. 0: sets the reference point at the beginning of the file, which is by default.
2. 1: sets the reference point at the current file position.
3. 1: sets the reference point at the end of the file.
Note: But in Python 3.x and above, we can seek from beginning only, if opened in text mode. We can
overcome from this by opening the file binary mode.
2. tellp() function – This function returns the position of current file pointer.
Syntax – <filepointer>.tell()
Example – f=open("temp.txt","rb")
f.seek(9)
f.seek(-9,1)
print(f.read(5))
print(f.tell())
f.seek(9,1)
print(f.read(12))
print(f.tell())
f.seek(-9,2)
print(f.read())
print(f.tell())
Write records in a binary file –
def write():
f=open("student.dat",'wb')
record=[ ]
while True:
rno=int(input("Enter roll no:"))
name=input("Enter Name:")
marks=int(input("Enter Marks:"))
data=[rno,name,marks]
record.append(data)
ch=input("Dou you want to enter more records?(y/n)")
if ch=='n':
break
pickle.dump(record,f)
Read records from a binary file –
def read():
f=open("student.dat","rb")
while True:
try:
s=pickle.load(f)
for i in s:
print(i)
except EOFError:
break
f.close()
Search a record in a binary file –
def search():
f=open("student.dat",'rb')
s=pickle.load(f)
found=0
rno=int(input("Enter the roll no whose record you want to search"))
for i in s:
if i[0]==rno:
print(i)
found=1
if found==0:
print("Record not found")
else:
print("Record found")
Update a record in a binary file –
def update():
f=open("student.dat",'rb+')
s=pickle.load(f)
found=0
rno=int(input("Enter the roll no whose record you want to update"))
for i in s:
if rno==i[0]:
print("Current name:",i[1])
i[1]=input("Enter the updated name")
found=1
break
if found==0:
print("Record not found")
else:
f.seek(0)
pickle.dump(s,f)
Append records in a binary file –
def append():
f=open("student.dat",'ab')
record=[ ]
while True:
rno=int(input("Enter roll no:"))
name=input("Enter Name:")
marks=int(input("Enter Marks:"))
data=[rno,name,marks]
record.append(data)
ch=input("Dou you want to enter more records?(y/n)")
if ch=='n':
break
pickle.dump(record,f)

You might also like