0% found this document useful (0 votes)
123 views60 pages

File Handling 2022 - Complete Notes

The document discusses file handling in Python. It begins by explaining that file handling allows Python programs to permanently store and retrieve data from disk files. It then discusses the different types of files that can be used, including text files, binary files, and CSV files. The key file operations of opening, reading, writing, and closing files are also explained. Specific methods for reading and writing data from text files like read(), readline(), readlines(), write(), and writelines() are provided as examples.

Uploaded by

Ashwin Shukla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views60 pages

File Handling 2022 - Complete Notes

The document discusses file handling in Python. It begins by explaining that file handling allows Python programs to permanently store and retrieve data from disk files. It then discusses the different types of files that can be used, including text files, binary files, and CSV files. The key file operations of opening, reading, writing, and closing files are also explained. Specific methods for reading and writing data from text files like read(), readline(), readlines(), write(), and writelines() are provided as examples.

Uploaded by

Ashwin Shukla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

CHAPTER - 4

INTRODUCTION

FILE HANDLING is a mechanism by which we can


read data of disk files in python program or write back
data from python program to disk files.

 So far in our python program the standard input is


coming from keyboard an output is going to monitor
i.e. no where data is stored permanent and entered data
is present as long as program is running BUT file
handling allows us to store data entered through
python program permanently in disk file and later on
we can read back the data
WHY USE FILE ?

• Data used in variables is temporary in nature. Once the


application is closed, all the variables and data is lost.
So, to counter such problem there comes the concept of
files.
• In 0rder to save our data on some secondary storage
devices, we have to use files.
• Data stores in files are permanent in nature.
• Python allows us to read data from and save data to
external files permanently on secondary storage device.
• File: A file (or Data file ) is a stream or sequence of
characters/data. It is named place on disk where a
sequence of related data is stored.
DATA FILE OPERATIONS

Python file handling takes place in following order:


1. Opening a file: ( Before we start working on file, first we need to
open it.)
2. We can perform various operations like- read, write, append, insert,
delete, etc.
3. Closing the file.
Note: We can process file in several ways, such as:
• Creating a file
• Traversing a file for displaying data on screen
• Appending or inserting data to file
• Deleting data from file
• Creating a copy of a file
• Updating data in a file
TYPES OF FILE

Before we discuss these file operations, we should be aware


of the file types.

• Python allows us to create and manage three types of


data files:

 Text file
 Binary file
 CSV file
TYPES OF FILE

Text file: A Text file consists of sequence of lines and each


line is terminated with a special character i.e. is newline( ‘\n’ )
character.
• A line is a sequence of characters ( ASCII or UNICODE )
which usually consists alphabets, numbers and other
special symbols.
• Easy to read strings from plain text files.
• Most operating systems come with basic tools to view and
edit them.
• Text files good choice for simple information
• Easy to edit
• Human readable! ( abc.txt )
TYPES OF FILE

• Binary file: data is stored in same format as it is held


in memory, so interpreting the correct data type while
reading the file is very important.
• It can be used to store complex data structures like
list and dictionary.
• In binary file there is no delimiter for a line, No
character translation carried out in binary file. As a
result, binary files are easier and much faster than
text files while reading and writing operation on data.
CSV FILE

• CSV stands for Comma Separated Values.


• CSV file is a type of plain text file means data stored in form of
ASCII or Unicode characters
• Each line is a row and in row each piece of data is separated by a
comma
• It is common format for data interchange
• CSV file example:-
Roll No., Name, Marks
1,Vinit,30
2,Alka,26
3,Rohit,28
Note: other delimiter which can be used with CSV file are tab(‘\t’),
colon(:), and semicolon(;).
BASIC OPERATIONS ON A TEXT
FILE

• File processing takes place in the following order.


• Open a file that returns a filehandle.
• Use the handle to perform read or write action.
• Close the filehandle.
OPEN A FILE

OPEN A FILE
• Python‟s built-in open() function
−It is used to open a file and return a file object .
−File objects contain methods and attributes about the file
− open() is most commonly used with two arguments
−Syntax:- file_object_name = open(filename, mode)
• The first argument is the filename
– Example :- f=open(“intro.txt")
– file extension is .txt
– Python looks in the current directory for the file
• The second argument is the file access mode
FILE ACCESS MODES
OPEN A FILE

• Open file by using with statement


• Syntax:-
with open(“demo.txt”, “r”) as f:
• With statement ensure all resources allocated to file
object gets deallocated automatically once we stop
using file.
• there is no need to call file.close()
ABSOLUTE OR RELATIVE PATH

Python can access a file in any directory by providing the proper


path
• Absolute path contains the full path to the file and not only the
file. It always starts at the same place, which is the root directory. For
Example
"C:\Users\itp\Desktop\words.txt"
• Relative path describes the location of a file or folder in relative to
the current working directory. For example
"data\words.txt"
CLOSE A FILE

Use the close() method to close a text file


f.close()
• Whenever you are done with a file, it is good programming
practice to close it
•It will release the resources allocated to file
READING FROM FILE

• Reading a character by using read() funtion


• Use the read(n) function to read the next n
number of characters
• Python remembers where it last read, and each subsequent
read(n) begins where the last ended
• To start back at the beginning of a file, close the file and open
it.
• If you don't specify a number, Python returns the entire
file as a string
EXAMPLE

EXAMPLE 1:- character wise analysis


Write a function to count a specific character

def count_specific(): # defining a function


f=open(“demo.txt",'r') # open file in read
c=0 # variable to count
a=f.read() # read all content and store in string
for i in a: # iterate through all character one by one
if i=='s': # condition
c=c+1 # increment /display
print("No of s in file=",c)
f.close() #close the file
count_specific() # call the function to perform the task
EXAMPLE

EXAMPLE 2:- word wise analysis


Write a function to count a word

def count_the():
f=open(“demo.txt",'r')
c=0
a=f.read() # read all content and store in string
b=a.split() # split the string into words
for i in b: # iterate through all words one by one
if i.lower()=="the": # condition
c=c+1 # increment /display
print("No of The word =",c)
f.close() #close the file
READING CHARACTERS FROM A LINE

• Use the readline(n) method where n is the number


of characters you want to read from the current line
• The method returns the characters as a string
• Once you read all of the characters of a line, the
next line becomes the current line
• If you don't pass a number, the method returns the
entire line
• readline() reads characters from the current line
only, while read() reads characters from the entire
file
LINES

• Reading all lines into a list


– Use the readlines() method to read a text file
into a list where each line of the file becomes a
string element in the list
• difference between readline() and readlines()
- readline() read character from one line and
readlines() read all line
- readline() return string and readlines() return list of
string
Ex: write python code to display each word of a line separately as
an element of a list.

myobject=open("myfile.txt",'r')
d=myobject.readlines()
for line in d:
words=line.split()
print(words)

O/P:
2 WAYS OF WRITING TO A TEXT FILE

• Writing strings to a text file


– Use the write(string) method which writes a
string to a text file
– write() does not automatically insert a newline
character at the end of a string
– You have to put newlines in where you want
them (use \n)
• Writing a list of string to a text file
– Use the writelines(list) method
WRITING AND READING TO A TEXT FILE

fobject=open("text_file3.txt","w")
sentence=input("Enter the contents to be written in
the file: ")
fobject.write(sentence)
fobject.close()
print("Now reading the contents of the file: ")
fobject=open("testfile.txt","r")
for str in fobject:
print(str)
fobject.close()
OUTPUT
EX: Entering student name to the text file using write() with “w”
mode:

# program to Enter student name using write():


fh = open("student.txt","w")
for i in range(5):
name = input("Enter name of student: " )
fh.write(name)
fh.write('\n')
fh.close()
print("\nData Saved Successfully....")
OUTPUT
Write using “a” mode

# program to Enter student name using write()


with append mode:
fh = open("student.txt","a")
for i in range(3):
name = input("Enter name of student: " )
fh.write(name)
fh.write('\n')
fh.close()
print("\nData Saved Successfully....")
OUTPUT
ENTERING DATA TO TEXT FILE USING writelines ( )

# using writelines() method:


myfile = open("emp.txt","w")
mylist = []
for i in range(3):
name = input("Enter employee name: ")
mylist.append(name + '\n')
myfile.writelines(mylist)
myfile.close()
print("Data Saved Succesfully....")
EX- WRITING STRING AS A RECORD TO A FILE

myfile = open("book.txt","a")
ans='y'
while ans=='y':
book_no=int(input("Enter Book Number: "))
book_name=input("Enter Book Name: ")
author=input("Enter Author Name: ")
price=int(input("Enter Book Price: "))

book_record=str(book_no)+","+book_name+","+author+","+str(price)+'\n'
myfile.write(book_record)
ans=input("Want to add more data ?")
myfile.close()
print("Data Added Successfully....")
EX- TO COPY DATA FROM ONE FILE TO ANOTHER FILE

#to copy the content of one file to another file


file1 = open("book.txt","r")
file2 = open("book_backup.txt","w")
str1=" "
while str1:
str1 = file1.readline( )
file2.write(str1)
file1.close( )
file2.close( )
print("data copied successfully....")
flush( ) function
 When we write any data to file, python hold
everything in buffer (temporary memory) and pushes it
onto actual file later. If you want to force Python to
write the content of buffer onto storage, you can use
flush() function.
 Python automatically flushes the files when closing
them i.e. it will be implicitly called by the close(), BUT
if you want to flush before closing any file you can use
flush()
EX- WORKING OF flush( ) Nothing is in
the file
temp.txt
Without flush()
myfile = open("temp.txt","w+")
myfile.write("Hello Student\n")
myfile.write("Welcome to the CS
class.\n")
n = input("Press any key..")
myfile.write("start learing the Python.\n")
myfile.close()
When you run the above code, program will
stopped at “Press any key”, for time being
don’t press any key and go to folder where file
“temp.txt” is created an open it to see what is
in the file till now
Now content is stored,
NOW PRESS ANY KEY…. because of close() function,
contents are flushed and
pushed in file.
All contents
EX- WORKING OF flush( ) before
flush() are
With flush() present in
file
myfile = open("temp.txt","w+")
myfile.write("Hello Student\n")
myfile.write("Welcome to the CS
class.\n")
myfile.flush()
n = input("Press any key..")
myfile.write("start learing the Python.\n")
myfile.close()

When you run the above code, program will


stopped at “Press any key”, for time being
don’t press any key and go to folder where file
“temp.txt” is created an open it to see what is Rest of the content is
in the file till now written because of close(),
contents are flushed and
NOW PRESS ANY KEY…. and pushed in file.
REMOVING WHITESPACES AFTER READING FROM FILE

 read() and readline() reads data from file and


return it in the form of string and readlines()
returns data in the form of list.
 All these read function also read leading and
trailing whitespaces, new line characters. If you
want to remove these characters you can use
functions
 strip() : removes the given character from both ends.
 lstrip(): removes given character from left end
 rstrip(): removes given character from right end
EX- strip( ) , lstrip( ) and rstrip( )

# use of strip(), lstrip() and rstrip()


myfile = open("quotes1.txt")
line1=myfile.readline()
print("length of line is: ",len(line1))
line1 = line1.rstrip('\n')
print("length of line is: ",len(line1))
line2 = myfile.readline()
print("length of line is: ",len(line2))
line2 = line2.lstrip()
print("lenght of line is: ",len(line2))
SETTING OFFSETS IN A FILE

The function till now are used to access the data


sequentially from a file. But if we want to access data in a
random manner, then Python gives us seek( ) and tell( )
fuction to do so.
• tell( ) This function returns an integer that specifies
the current position of the file object in the file. The
position so specified is the byte position from the
beginning of the file.
• file_object.tell( )
SETTING OFFSETS IN A FILE

• seek( ) This method is used to position the file object at a


particular position in a file.
• file_object.seek( offset, refr_point)
• In the above syntax, offset is the number of bytes by which the file
pointer is to be moved.
• reference_point indicates the starting position of the file_object
i.e. with reference to which position, the offset has to counted.
It can have any of the following values:
0 – beginning of the file
1 – current position of the file
2 – end of the file
By default, the value of rfr_point is 0, i.e. offset count from
beginning of file.
PROGRAM THAT TELLS AND SET THE POSITION OF POINTER

# program to set the offset of file pointer


file_obj = open("text_file.txt","rb")
print("Position of file pointer before reading is: ",file_obj.tell())
print(file_obj.read(10))
print("Position of file pointer after reading is: ",file_obj.tell())
print("Setting 3 bytes from the current position of file pointer")
file_obj.seek(3,1)
print(file_obj.read())
file_obj.close()
STANDARD INPUT / OUTPUT AND
ERROR STREAMS

The standard devices are treated as file and often referred to as


“streams”.
• Standard input (stdin) read data from keyword
• Standard output (stdout) make output on monitor
• Standard error (stderr) output error on monitor
• In python sys module help to use these standard stream
• Example:-
import sys
a=sys.stdin.read(5)
sys.stdout.write(“hi”)
EXAMPLE

EXAMPLE 1:- Use of standard stream


Write a program to check whether a number is prime or not.

import sys
sys.stdout.write("enter number to be checked") # output on screen
a=int(sys.stdin.read(2)) # read from keyboard
for i in range(2,a):
if a%i==0:
sys.stdout.write("not a prime") # output on screen
break
else:
sys.stderr.write("prime") # output in red color
BASIC OPERATIONS ON A BINARY
FILE

• binary file is also opened and closed in same way as text file by open() function
and close() function respectively but extension of file is .dat and mode of opening
binary file is given below:
Syntax:- file_object=open('data.dat', 'wb')
PICKLE

• pickle module can be used to store any kind of object in file as


it allows us to store python objects with their structure. pickle
module converts Python object into a series of bytes. The byte
stream representing the object can be transmitted or stored,
and reconstructed to create a new object with the same
characteristics.
• “Pickling” is the process whereby a Python object is converted
into a byte stream
• “unpickling” is the process whereby a byte stream (from
a binary file) is converted back into an object
PICKLE

• Function in pickle module


• load()- Read and return an object from the pickle data stored
in a file
• dump()- Write a pickled representation of obj to the open file
object file
TO CREATE AND READ A BINARY FILE

To Create a Binary File we use the following Syntax:

File_object = open(“file_name.dat”,”wb”)

To read a binary file:

File_object = open(“file_name.dat”, “rb”)


WRITING DATA TO BINARY FILE USING : dump( )

Ex: Program to get student details from user and wirte input data to the binary file.
import pickle
stud = { }
fh = open("stud.dat","wb")
ans='y'
while ans=='y':
roll = int(input("Enter roll no.: "))
name = input("Enter name: ")
percent = int(input("Enter percentage of marks: "))
stud["Roll no."] = roll
stud["Namee"]= name
stud["percentage"]=percent

pickle.dump(stud, fh)
ans=input("want to enter more record press: y else n: ")

fh.close()
EX: write
a program to write employee data to the binary file
named emp.dat from the dictionary
import pickle
emp1={"Emp_no":101, "Name":'Anushka', 'Age':28, 'Salary':52000}
emp2={"Emp_no":102, "Name":'Virat', 'Age':29, 'Salary':72000}
emp3={"Emp_no":103, "Name":'Manshi', 'Age':24, 'Salary':43000}
emp4={"Emp_no":104, "Name":'Ankit', 'Age':26, 'Salary':29000}
emp5={"Emp_no":105, "Name":'Vijay', 'Age':29, 'Salary':46000}

fh = open("emp.dat","wb")
pickle.dump(emp1,fh)
pickle.dump(emp2,fh)
pickle.dump(emp3,fh)
pickle.dump(emp4,fh)
pickle.dump(emp5,fh)

print("Data written successfully....")


fh.close()
READ FROM A BINARY FILE

# read data from stud.dat file


import pickle
fh = open("stud.dat","rb")
try:
while True:
data = pickle.load(fh)
print(data)

except EOFError:
fh.close()
APPEND INTO BINARY FILE

Ex: program to append new student data to the previously created


stud.dat file

import pickle
stud={}
fob = open("stud.dat","ab")
ans='y'
while ans=='y':
roll = int(input("Enter roll no.: "))
name = input("Enter name: ")
percent = int(input("Enter percentage of marks: "))
stud["Roll no."] = roll
stud["Name"]= name
stud["percentage"]=percent
#write into the file
pickle.dump(stud, fob)
ans=input("want to enter more record press: y else n: ")
fob.close()
READ FROM A BINARY FILE
AFTER APPENDING DATA

# read student data after appending data to stud.dat file


import pickle
fh = open("stud.dat","rb")
try:
while True:
data = pickle.load(fh)
print(data)

except EOFError:
fh.close()
# program to search student with roll no.
import pickle
stud ={} SEARCH IN BINARY FILE

file = open("stud.dat","rb")
search_roll = int(input("Enter roll no. to be search: "))
found = False
#read data from the stud.dat file
try:
print("Seraching in file stud.dat....")
while True:
stud = pickle.load(file)
if stud["Roll no."] == search_roll:
print(stud)
found = True
except EOFError:
if found==False:
print("No such record found in the file.")
else:
print("Search successful.")
# program to search student who got more than 85 %
import pickle
stud={ } SEARCH STUDENT % > 85

found = False
print("Searching in Stud.dat file...")
#open stud.dat file in read mode
fh = open("stud.dat","rb")
try:
while True:
stud=pickle.load(fh)
if stud["percentage"]>85:
print(stud)
found=True
except EOFError:
if found == False:
print("No such student found...")
else:
print("search scuccessful.")
fh.close()
# program to update the marks of student who got less than 85 by 2.
import pickle
stud ={} UPDATE DATA IN BINARY FILE
found =False
#open stud.dat file in read and write mode.
fh = open("stud.dat","rb+")
try:
while True:
f_pointer = fh.tell()
stud = pickle.load(fh)
if stud["percentage"]< 85:
stud["percentage"]= stud["percentage"] + 2
fh.seek(f_pointer)
pickle.dump(stud,fh)
found = True
except EOFError:
if found == False:
print("No such student found.")
else:
print("Record(s) successfully updated.")
fh.close()
# program to modify the name of student whose roll no. is 05 by Arman.
import pickle
stud ={}
found =False UPDATE DATA IN BINARY FILE
fh = open("stud.dat","rb+")
try:
while True:
f_pointer = fh.tell()
stud = pickle.load(fh)
if stud["Roll no."] == 5:
stud["Name"]= "Arman"
fh.seek(f_pointer)
pickle.dump(stud,fh)
found = True
except EOFError:
if found == False:
print("No such record found.")
else:
print("Record(s) successfully updated.")
fh.close()
CSV MODULE

• csv module provides classes that assist in the reading and


writing of Comma Separated Value (CSV) files
• Statement to import csv module:-
import csv
• To open a csv file, use open() function as used previously in
text and binary file.
• Syntax:- file_object=open(„filename.csv', „mode')
• f=open('data.csv', 'w')
• To close a csv file, use close() function as used previously in
text and binary file.
• Syntax:- file_object.close()
FUNCTION IN CSV MODULE

• csv.reader :- It is a built-in function in module csv. It take file


object as an argument and The returned object is an iterator. Each
iteration returns a row of the CSV file
• Syntax:- csv_reader = csv.reader( file_object)
• csv.writer:-It is a built-in function in module csv. It take file object
and returns a writer object responsible for converting the user‟s
data into delimited strings. Writer object have public methods
which are used to write content in csv file like writerow( ) and
writerrows( )
• Syntax :- wrt = csv.writer(file_object)
• wrt.writerow(d1,d2,d3)
WRITE DATA INTO CSV FILE

Ex 1 – Write a program to create a csv file to store student data , take data
from user and write record into it.
import csv
fh = open("student.csv","w")
stud_writer = csv.writer(fh)
header=["Roll_no", "Name", "Marks"]
stud_writer.writerow(header)

for i in range(5):
print("Enter Student " + str(i+1) +" Data: ")
roll = int(input("Enter Roll_no: "))
name = input("Enter Student's Name: ")
marks = float(input("Enter Marks in CS: "))

stud_rcd = [roll,name,marks]
stud_writer.writerow(stud_rcd)
fh.close()
WRITE DATA INTO CSV FILE USING
writerows( )
Ex 1 – Write a program to create a csv file to store student data ,
using list of records.
import csv
fh = open("student1.csv","w")
writer = csv.writer(fh)
stud_data = [ ["Roll","Name","Marks"],
[1,"Aditya",95],
[2,"Vishnu",96],
[3,"Anushka",89],
[4,"Virat",85],
[5,"Rahul",94]
]
writer.writerows(stud_data)
fh.close()
print("Data written successfully...")
READ FROM CSV FILE

# read data from csv file


import csv
fh = open("student.csv")
reader = csv.reader(fh)
for rec in reader:
print(rec)
READ FROM CSV FILE

Read csv file data while opening file using newline=‘\r\n’

# read data from csv file


# open file using newline ='\r\n'
import csv
fh = open("student1.csv","r", newline='\r\n')
reader = csv.reader(fh)
for rec in reader:
print(rec)
Note: We use newline argument while opening the csv file to discard to ignore
the translation of newline character done while reading the csv file and print the
extra emplty list [ ] in previous example.
THANK YOU

You might also like