FILE HANDLING IN PYTHON NOTES Final
FILE HANDLING IN PYTHON NOTES Final
Those data are to be retrieved later on,then the concept of file handling comes. It is
impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the file system which is not volatile
and can be accessed every time. File handling in Python enables us to create, update,
read, and delete the files stored on the file system through our python program. The
following operations can be performed on a file.
Types of File :
Text Files:
A file whose contents can be viewed using a text editor is called a text file. A text file
is simply a sequence of ASCII or Unicode characters. Python programs, contents
written in text editors are some of the example of text files.
Binary Files:
A binary file stores the data in the same way as as stored in the memory. The .exe
files,mp3 file, image files, word documents are some of the examples of binary
files.we can’t read a binary file using a text editor.
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.
STEPS TO PROCESS A FILE
Before any reading or writing operation of any file,it must be opened first of
all.Python provides built in function open() for it. It accepts two parameters :
filename, and mode.
Syntax:
<file_object_name> = open(<file_name>,<mode>)
Example: f = open(“demo.txt”,”r”)
File Objects:
Description
Mode
Read Default value. Opens a file for reading, error if the file
“r” does not exist.
Write Opens a file for writing, creates the file if it does not
“w” exist
Append Opens a file for appending, creates the file if it does
“a” not exist
Read and File must exist otherwise error is raised.Both reading
“r+” Write and writing operations can take place.
File is created if it does not exist.If the file exists past
“w+” Write and data is lost (truncated).Both reading and writing
Read operations can take place.
Append and File is created if it does not exist.If the file exists past
“a+” Read data is lost (truncated).Both reading and writing
operations can take place.
CLOSING A FILE
close():
Used to close an opened file. After using this method, an opened file will be closed
and a closed file cannot be read or written any more. It is important to close your
files, as in some cases, due to buffering, changes made to a file may not show until
you close the file.
Syntax:
<fileObject>.close()
Example : f.close()
1. read() METHOD
2. readline() METHOD
3. readlines() METHOD
read() METHOD
By default the read() method returns the whole text, but you can also specify how many
characters you want to return by passing the size as argument.
Syntax:
f = open("demo.txt", "r")
readline() METHOD
Syntax:
<file_object>.readline()
Example
f = open("demo.txt", "r")
print(f.readline())
#This program will return the first line in the file “demo.txt” irrespective of #number
of lines in the text file.
readlines() METHOD
readlines() method will return a list of strings, each separated by \n. readlines() can
be used to read the entire content of the file.
Syntax:
<file_object>.readlines()
Example :
f = open("demofile.txt", "r")
print(f.readlines())
The read() reads from a file in read mode, and stores its contents in a string type
variable. It can either read the whole content from the file if a parameter is not passed and
reads only as many characters as the size passed to the read().
The readline() function reads from a file in read mode and returns the next line in the file or
a blank string if there are no more lines. The return data type is of string type.
The readlines() function, also reads from a file in read mode and returns a list of all lines in
the file. The returned data is of list type.
A Program writes into a text/binary file in hard disk.Followings are the methods to
write a data to the file:
o write () METHOD
o writelines() METHOD
If you open a file in in “w” or write mode , Python overwrites an existing file or
creates a non- existing file. For an existing file with the same name , the earlier data
gets lost.
If you want to write into a file while retaining the old data , the file must be opened in
append or “a” mode.
write() Method
write() method takes a string ( as parameter ) and writes it in the file. For
storing data with end of line character, you will have to add \n character to
end of the string.
Example:
f = open("demo_write.txt", "a")
f.close()
f = open("demo_write.txt", "r") #open and read the file after the appending
print(f.read())
writelines() METHOD
For writing a string at a time, we use write() method, it can't be used for
writing a list, tuple etc. into a file. Python file method writelines() writes
a sequence of strings to the file. The sequence can be any iterable object
producing strings, typically a list of strings.So, whenever we have to
write a sequence of string / data type, we will use writelines(),
instead of write().
# Program to demostrate writelines()
f = open("demofile.txt", "a")
f.writelines(["We love python!", "\nFile Handling"])
f.close()
When you write on to a file using any of the write functions, Python holds
everything to write in the file and pushes it onto actual file on storage device at a later
time. So to force Python t write the contents onto files you can use flush().
The flush() function forces the writing of data on disc still pending in the
output buffer.
Syntax :
<file_object>.flush()
# Program to demostrate flush()
f = open("demo_flush.txt","w+")
f.write("India is my country.\n")
f.flush()
f.write(x)
f.close()
Exception Handling
An exception is a python object that represents an error. The exception needs to be handled bythe
programmer so that the program does not terminate abruptly.
Eg:
Try and Except Block: An exception is caught in the try block and handled in except block.An
exception is said to be caught when a code designed to handle a particular exception is executed.
While executing the program if an exception is encountered further execution of the code insidethe
try block is stopped and the control is transferred to the except block.
try...except…else clause:
We can put an optional else clause along with the try...except clause. An except block will be executed
only if some exception is raised in the try block. But if there is no error then none of the except blocks
will be executed. In this case, the statements inside the else clause will be executed.
Eg:
try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)
Finally clause:
The try statement in Python can also have an optional finally clause. The statements inside the
finally block are always executed regardless of whether an exception has occurred in the try block
or not.
Some of the commonly occurring built-in exceptions are :
The seek() method: This method is used to position the file object at a particular position in a
file. The syntax of seek() is: file_object.seek(offset ,[ reference_point])
In the above syntax, offset is the number of bytes by which the file object is to be moved.
reference_point indicates the starting position of the file object. That is, with reference to which
position, the offset has to be counted. It can have any of the following values:
- beginning of the file
- current position of the file
- end of file
By default, the value of reference_point is 0, i.e. the offset is counted from the beginning of the
file. For example, the statement fileObject.seek(5,0) will position the file object at 5th byte
position from the beginning of the file.
BINARY FILES:
Files that store objects as some byte stream are called binary files. That is, all the
binary files are encoded in binary format , as a sequence of bytes, which is understood
by a computer or machine. In binary files, there is no delimiter to end the line. Since
they are directly in the form of binary, there is no need to translate them. But they are
not in human readable form and hence difficult to understand.
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
to a byte stream before writing 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.
import pickle
pickle.dump() method is used to write the object in file which is opened in binary access
mode.
Syntax :
pickle.dump(<structure>,<FileObject>)
Here 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.
import pickle
f = open("binary_file1.dat","wb")
city = ["Banglore","Delhi","Hyderabad"]
pickle.dump(city,f)
f.close()
pickle.load() Method
pickle.load() method is used to read data from a file
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
import pickle
f=open("binary_file1.dat","rb")
lst = pickle.load(f)
print("Content in binary file is : ")
print(lst)
f.close()
CSV FILES :
CSV stands for Comma Separated Values. It is a type of plain text file that uses
specific structuring to arrange tabular data such as a spreadsheet or database.
CSV like a text file , is in a human readable format and extensively used to store
tabular data, in a spreadsheet or database. Each line of the 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.
To read data from csv files, reader function of csv module is used. csv.reader()
returns a reader object.It loads data from a csv file into an iterable after parsing
delimited data.
STEPS TO READ
To write data into csv files, writer() function of csv module is used.
csv.writer():
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() :