0% found this document useful (0 votes)
3 views11 pages

CH 2 - File Handling in Python

Uploaded by

mr.bhagath.k
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)
3 views11 pages

CH 2 - File Handling in Python

Uploaded by

mr.bhagath.k
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

CHAPTER-2

FILE HANDLING IN PYTHON


2.1 Introduction to files
File:
A file is a named location on a secondary storage media where data are
permanently stored for later access.
File Handling:
File handling is the process of working with files like creating, reading,
writing, updating, and deleting them using programming languages. It allows
programs to store and retrieve data from external storage (like a hard disk
or SSD).

2.2 Types of files


Types of files.
i) Text file
ii) Binary file

Text File:
 A text file is a sequence of characters, including letters, numbers, and
symbols.
 It stores information as ASCII or UNICODE values,
 A text editor converts these values into readable characters.
 Each line ends with a special character End of Line (EOL).
 Examples: Files with extensions like .txt, .py, .csv, etc. are text files.

Binary files.
 A binary file stores the information in the form of bytes (0s and 1s).
 These bytes do not represent the ASCII values of characters.
 These files are not human readable. So it is difficult to remove any error.
 Specific software is required to read or write the contents of a binary file.
 Examples: Files with extensions like .obj, .dat, are binary files.

Differentiate between text file and binary file.

Text file Binary file


A text file is a sequence of they represent the actual content
characters including letters, such as image, audio, video,
numbers and digits. executable files, etc.
It stores information as ASCII or A binary data stores the
UNICODE values. information in the form of bytes(0s
and 1s)
These files are human readable These files are not human readable
Each line ends with a special End Of Line (EOL) is not required
character , End Of Line (EOL)
Can be modified in simple text Special software is required to
editors. modify the binary file.
Example:.txt,.doc,.py are text Example: .dat,.obj ,jpeg are binary
files. files.

2.3 Opening and Closing a Text File


Opening a File.
a) To open a file in Python, we use the open() function.
syntax of open()
file_object= open(filename, access_mode)
b) This function returns a file object called file handle which is stored in
the variable file_object.
c) The file_object has certain attributes that tells us basic information
about the file, such as:
i)<[Link]> returns true if the file is closed and false
otherwise.
ii)<[Link]> the access mode in which the file was opened.
iii)<[Link]> returns the name of the file.
d) The file_name should be the name of the file that has to be opened.
e) The access_mode is an optional argument that represents the mode
in which the file has to be accessed by the program. It is also
referred to as processing mode.
Example :
myobject=open(“[Link]”,”r”)
File Access Modes

Closing a File:
a) Python provides a close() method to close a file. While closing a file, the
system frees the memory allocated to it.
Syntax:
file_object.close()
b) Python makes sure that any unwritten or unsaved data is written to the
file before it is closed.

Opening a File using with clause:


syntax:
with open (file_name, access_mode) as file_ object:
The advantage of using with clause is that any file that is opened using
this clause is closed automatically.
Example
with open(“[Link]”,”r+”) as myObject:
content = [Link]()
2.4 Writing to a Text File.
For writing to a file, we first need to open it in write or append mode.
• write() - for writing a single string
• writelines() - for writing a sequence of strings
write() method.
a) write() method takes a string as an argument and writes it to the
text file.
b) It returns the number of characters being written on single
execution of the write() method.
c) in write() method, we need to add a newline character (\n) at the
end of every sentence to mark the end of line. ‘\n’ is treated as a
single character.
Example :

writelines() method.
a) This method is used to write multiple strings to a file. We need to
pass an iterable object like lists, tuple, etc. containing strings to
the writelines() method.
b) the writelines() method does not return the number of characters
written in the file.
Example :

Differentiate between write() and writelines().

write() writelines()
The write() method is used to The writelines() method is used
write a single string to a file. to write multiple strings to a file.
The writelines() method takes
The write() method takes a an iterable object like lists,
string as an argument. tuple, etc. containing strings as
an argument.
The write() method returns the The writelines() method does
number of characters written on not return the number of
to the file. characters written in the file.
2.5 Reading from a text file
a) We can write a program to read the contents of a file. Before
reading a file, we must make sure that the file is opened in “r”, “r+”,
“w+” or “a+” mode.
b) There are three ways to read the contents of a file:
i) The read() method.
ii) The readline([n]) method.
iii) The readlines() method.

read() method:
a) This method is used to read a specified number of bytes of data
from a data file.
b) syntax:
file_object.read(n)
Example:

c) If no argument or a negative number is specified in read(), the


entire file content is read.
readline([n]) method:
a) This method reads one complete line from a file where each line
terminates with a newline (\n) character.
b) It can also be used to read a specified number (n) of bytes of data
from a file but maximum up to the newline character (\n).
Example :

c) If no argument or a negative number is specified, it reads a complete


line and returns string.
d) To read the entire file line by line using the readline(), we can use a
loop. This process is known as looping/ iterating over a file object.
readlines() method:
a) The readlines() method is used to read all lines from a file and return
them as a list of strings, where each string represents a line from the
file.
b) When we read a file using readlines() function, lines in the file become
members of a list, where each list element ends with a newline
character (‘\n’).
Example :

c) In case we want to display each word of a line separately as an


element of a list, then we can use split() function.

d) if splitlines() is used instead of split(), then each line is returned


as element of a list.

Python program writing and reading to a text file.

2.6 Setting offsets in a file.

If we want to access data in a random fashion, then Python gives us seek() and
tell() functions to do so.
 tell()method:

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 till the current position of the file object.

Syntax:
file_object.tell()
seek() method :
This method is used to position the file object at a particular position in a
file.
Syntax:
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:
0 - beginning of the file
1 - current position of the file
2 - end of file
By default, the value of reference point is 0, i.e. the offset is counted from
the beginning of the file.
Example: the statement [Link](5,0) will position the file object
at 5th byte position from the beginning of the file.
Python program for application of seek() and tell().
2.7 Creating and traversing a text file
Creating a file and writing data:
a) To create a text file, we use the open() method and provide the filename
and the mode.
b) If it is in write mode (w), then all the existing contents of file will be lost,
and an empty file will be created with the same name.
c) if the file is created in append mode (a), then the new data will be written
after the existing data.
d) In both cases, if the file does not exist, then a new empty file will be
created.
# program to create a text file and add data

Traversing a file and displaying data.


a) Traversing a file means reading its contents line by line and
processing the data.
b) This can be done using different file reading methods like read(),
readline(), readlines(), or simply iterating over the file object.
c) The file will be opened in read mode and reading will begin from the
beginning of the file.
Program: To display data from a text file

2.8 The Pickle Module


 Python provides a module called Pickle. The module Pickle is used
for serializing and de-serializing any Python object structure.
 The pickle module deals with binary files. Here, data are not written
but dumped and similarly, data are not read but loaded. The pickle
module must be imported to load and dump data.
 The pickle module provides two methods - dump() and load() to
work with binary files for pickling and unpickling, respectively.
Serialization:
Serialization is the process of transforming data or an object in memory
(RAM) to a stream of bytes called byte streams. These byte streams in
a binary file can then be stored in a disk or in a database or sent through
a network. Serialization process is also called pickling.
Deserialization:
De-serialization or unpickling is the inverse of pickling process where a
byte stream is converted back to Python object.

Dump() method.
This method is used to convert (pickling) Python objects for writing data in
a binary file. The file in which data are to be dumped, needs to be opened
in binary write mode (wb).
Syntax:
dump(data_object, file_object)
where data_object is the object that has to be dumped to the file
with the file handle named file_object.

Program: Pickling data in Python.


import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("[Link]", "wb")
[Link](listvalues, fileobject)
[Link]()

load() method:
This method is used to load (unpickling) data from a binary file. The
file to be loaded is opened in binary read (rb) mode.
Syntax: Store_object = load(file_object)
The pickled Python object is loaded from the file having a file handle
named file_object and is stored in a new file handle called store_object.
Program: Unpickling data in Python
import pickle
print("The data that were stored in file are: ")
fileobject=open("[Link]","rb")
[Link]()
[Link] between the following set of statements (a) and (b):
(a) P=open("[Link]", "r")
[Link](10)
(b) with open("[Link]", "r") asP:
x=[Link]()
Ans: The code given in (a) will open file "[Link]" in read mode and
will read 10 bytes from it. Also, it will not close the file explicitly. On
the other hand, the code given in (b) will open file "[Link]" in
read mode and will read the entire content of the file. Furthermore,
it will automatically close the file after executing the code due to the
with clause.

2. Answer the following


a. Open a file “[Link]” in “r” mode using with clause
b. Print the contents using appropriate function
Ans:
with open(“[Link]”, ”r”) as file:
data = [Link]( )
b. print(data)

3. Write the file mode that will be used for opening the following
files. Also, write the Python statements to open the following
files:
a) a text file “[Link]” in both read and write mode.
b) a binary file “[Link]” in write mode.
c) a text file “[Link]” in append and read mode.
d) a binary file “[Link]” in read only mode.

Ans: a)File Mode: 'r+'


fh=open("[Link]", "r+")
b) File Mode: 'wb'
fh=open("[Link]", "wb")
c) File Mode: 'a+'
fh=open("[Link]", "a+")
d) File Mode: 'rb'
fh=open("[Link]", "rb")

You might also like