Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

1

Reading and Writing to text files in Python

Python provides inbuilt functions for creating, writing and reading files.
There are two types of files that can be handled in python, normal text
files and binary files (written in binary language,0s and 1s).
 Text files: In this type of file, Each line of text is terminated with a
special character called EOL (End of Line), which is the new line
character (‘\n’) in python by default.
 Binary files: In this type of file, there is no terminator for a line and
the data is stored after converting it into machine understandable
binary language.

File Access Modes

Access modes govern the type of operations possible in the opened file. It
refers to how the file will be used once its opened. These modes also define the
location of the File Handle in the file. File handle is like a cursor, which defines
from where the data has to be read or written in the file. There are 6 access
modes in python.
1. Read Only (‘r’) : Open text file for reading. The handle is positioned at the
beginning of the file. If the file does not exists, raises I/O error. This is also
the default mode in which file is opened.
2. Read and Write (‘r+’) : Open the file for reading and writing. The handle is
positioned at the beginning of the file. Raises I/O error if the file does not
exists.
3. Write Only (‘w’) : Open the file for writing. For existing file, the data is
truncated and over-written. The handle is positioned at the beginning of the
file. Creates the file if the file does not exists.
4. Write and Read (‘w+’) : Open the file for reading and writing. For existing
file, data is truncated and over-written. The handle is positioned at the
beginning of the file.
5. Append Only (‘a’) : Open the file for writing. The file is created if it does not
exist. The handle is positioned at the end of the file. The data being written
will be inserted at the end, after the existing data.
6. Append and Read (‘a+’) : Open the file for reading and writing. The file is
created if it does not exist. The handle is positioned at the end of the file.
The data being written will be inserted at the end, after the existing data.
2

Opening a File

It is done using the open() function. No module is required to be imported for


this function.

File_object = open(r"File_Name","Access_Mode")

Closing a file

close() function closes the file and frees the memory space acquired by
that file. It is used at the time when the file is no longer needed or if it is
to be opened in a different file mode.

File_object.close()

Writing to a file
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
2. writelines() : For a list of string elements, each string is inserted in the text
file.Used to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Reading from a file
There are three ways to read data from a text file.
1. read() : Returns the read bytes in form of a string. Reads n bytes, if no n
specified, reads the entire file.
File_object.read([n])
2. readline() : Reads a line of the file and returns in form of a string.For
specified n, reads at most n bytes. However, does not reads more than one
line, even if n exceeds the length of the line.
File_object.readline([n])
3

3. readlines() : Reads all the lines and return them as each line a string
element in a list.
File_object.readlines()

Object Oriented Programming in Python


Class:
A class is a blueprint that defines the variables and the methods
(Characteristics) common to all objects of a certain kind.
Class Definition Syntax:

class ClassName:
# Statement-1
.
.
.
# Statement-N

# Python3 program to
# demonstrate defining
# a class

class Dog:
pass

Object:

The object is an entity that has a state and behavior associated with it. It may
be any real-world object like the mouse, keyboard, chair, table, pen, etc.
An Object is an instance of a Class. A class is like a blueprint while an instance
is a copy of the class with actual values.
4

An object consists of :
 State: It is represented by the attributes of an object. It also reflects the
properties of an object.
 Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
 Identity: It gives a unique name to an object and enables one object to
interact with other objects.
Types of inheritance Python
nheritance is defined as the capability of one class to derive or inherit
the properties from some other class and use it whenever needed.
Inheritance provides the following properties:

 It represents real-world relationships well.


 It provides reusability of code. We don’t have to write the same
code again and again. Also, it allows us to add more features to a
class without modifying it.
 It is transitive in nature, which means that if class B inherits from
another class A, then all the subclasses of B would automatically
inherit from class A.
 Single Inheritance: Single inheritance enables a derived class to inherit
properties from a single parent class, thus enabling code reusability and
the addition of new features to existing code.
5

Multiple Inheritance: When a class can be derived from more


than one base class this type of inheritance is called multiple
inheritance. In multiple inheritance, all the features of the base
classes are inherited into the derived class.

Multilevel Inheritance
In multilevel inheritance, features of the base class and the
derived class are further inherited into the new derived class. This
is similar to a relationship representing a child and grandfather.
6

Hierarchical Inheritance: When more than one derived classes


are created from a single base this type of inheritance is called
hierarchical inheritance. In this program, we have a parent (base)
class and two child (derived) classes.

Handling an exception
If you have some suspicious code that may raise an exception, you can
defend your program by placing the suspicious code in a try: block. After the
7

try: block, include an except: statement, followed by a block of code which


handles the problem as elegantly as possible.

Syntax
Here is simple syntax of try....except...else blocks −
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.

The except Clause with No Exceptions


You can also use the except statement with no exceptions defined as follows

try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.

The except Clause with Multiple Exceptions


You can also use the same except statement to handle multiple exceptions
as follows −
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
8

......................
else:
If there is no exception then execute this block.

The try-finally Clause


You can use a finally: block along with a try: block. The finally block is a
place to put any code that must execute, whether the try-block raised an
exception or not. The syntax of the try-finally statement is this −
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................

Example
Live Demo
#!/usr/bin/python

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"

If you do not have permission to open the file in writing mode, then this will
produce the following result −
Error: can't find file or read data

You might also like