UNIT-4
Syllabus:
File Operations: Understanding read functions, read (), readline () and readlines (),
Understanding write functions, write () and writelines (), Manipulating file pointer using seek,
Programming using file operations, Reading config files in python, Writing log files in python.
Object Oriented Programming: Concept of class, object and instances, Constructor, class
attributes and destructors, Real time use of class in live projects, Inheritance, overlapping and
overloading operators, Adding and retrieving dynamic attributes of classes, Programming
using Oops support.
Design with Classes: Objects and Classes, Data modelling Examples, Case Study An ATM,
Structuring Classes with Inheritance and Polymorphism.
Files in Python:
Until now, you have been reading and writing to the standard input and output. Now,
we will see how to use actual data files. Python provides us with an important feature for
reading data from the file and writing data into a file. Mostly, in programming languages, all
the values or data are stored in some variables which are volatile in nature. Because data will
be stored into those variables during run-time only and will be lost once the program execution
is completed. Hence it is better to save these data permanently using files. Python provides
basic functions and methods necessary to manipulate files by default. You can do most of the
file manipulation using a file object.
Opening and Closing Files
The open () Method
Before you can read or write a file, you have to open it using Python's built-in open
() function. This function creates a file object, which would be utilized to call other support
methods associated with it.
Syntax: file object = open (filename, access mode)
Here are parameter details –
file_name − The file_name argument is a string value that contains the name of the file that
you want to access.
access_mode − The access_mode determines the mode in which the file has to be opened, i.e.,
read, write, append, etc. A complete list of possible values is given below in the table. This is
optional parameter and the default file access mode is read (r).
Here is a list of the different modes of opening a file –
Sno Modes & Description
1
R
Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.
2 Rb
Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
3 r+
Opens a file for both reading and writing. The file pointer placed at the beginning of
the file.
4 rb+
Opens a file for both reading and writing in binary format. The file pointer placed at
the beginning of the file.
5 W
Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
6 Wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If
the file does not exist, creates a new file for writing.
7 w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists.
If the file does not exist, creates a new file for reading and writing.
8 wb+
Opens a file for both writing and reading in binary format. Overwrites the existing
file if the file exists. If the file does not exist, creates a new file for reading and
writing.
9 A
Opens aq file for appending. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file
for writing.
10 Ab
Opens a file for appending in binary format. The file pointer is at the end of the file
if the file exists. That is, the file is in the append mode. If the file does not exist, it
creates a new file for writing.
11 a+
Opens a file for both appending and reading. The file pointer is at the end of the file
if the file exists. The file opens in the append mode. If the file does not exist, it creates
a new file for reading and writing.
12 ab+
Opens a file for both appending and reading in binary format. The file pointer is at
the end of the file if the file exists. The file opens in the append mode. If the file does
not exist, it creates a new file for reading and writing.
The file Object Attributes:
Once a file is opened and you have one file object, you can get various information
related to that file.
Here is a list of all attributes related to file object −
Sno Attribute & Description
1 [Link]
Returns true if file is closed, false otherwise.
2 [Link]
Returns access mode with which file was opened.
3 [Link]
Returns name of the file.
Example:
f=open('[Link]','w') # creates a new file [Link] give write permissions on file
#File object attributes
print('Name of the file: ', [Link])
print('Closed or not : ', [Link])
print('Opening mode : ', [Link])
[Link]()
The close () Method
The close () method of a file object flushes any unwritten information and closes the
file object, after which no more writing can be done. It is a good practice to use the close ()
method to close a file.
Syntax: [Link]()
Example:
f=open('[Link]','w') # creates a new file [Link] give write permissions on file
#File object attributes
print('Name of the file: ', [Link])
print('Closed or not : ', [Link])
print('Opening mode : ', [Link])
[Link]()
Reading and Writing Files
The file object provides a set of access methods. Now, we will see how to use read (), readline
(), readlines () and write (), writelines () methods to read and write files.
Understanding write () and writelines ()
The write () Method
• The write () method writes any string (binary data and text data) to an open file.
• The write () method does not add a newline character ('\n') to the end of the string
Syntax: [Link](string)
Here, passed parameter is the content to be written into the opened file.
Example:
f=open('[Link]','w') # creates a new file [Link] give write permissions on file
#writing content into file [Link] using write method
[Link]( "Python is a great language.")
[Link]()
The Writeline () method:
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. There is no return value.
Syntax: [Link](sequence)
Parameters
Sequence − This is the Sequence of the strings.
Return Value-This method does not return any value.
Example
f=open('[Link]','w') # creates a new file [Link] give write permissions on file
#writing content into file using write method
[Link](['python is easy\n','python is portable\n','python is comfortable'])
[Link]()
Understanding read (), readline () and readlines ():
The read () Method
The read () method reads a string from an open file. It is important to note that Python strings
can have binary data. apart from text data.
Syntax: [Link]([count])
Here, passed parameter is the number of bytes to be read from the opened file. This method
starts reading from the beginning of the file and if count is missing, then it tries to read as
much as possible, maybe until the end of file.
Example
f=open('[Link]','w') # creates a new file [Link] give write permissions on file
#writing content into file using write method
[Link](['python is easy\n','python is portable\n','python is comfortable'])
[Link]()
f=open('[Link]','r')
#reading first 20 bytes from the file using read() method
print([Link](20))
The readline () Method
Python file method readline()reads one entire line from the file. A trailing newline character
is kept in the string. If the size argument is present and non-negative, it is a maximum byte
count including the trailing newline and an incomplete line may be returned.
An empty string is returned only when EOF is encountered immediately.
Syntax: [Link]( size )
Parameters
• size − This is the number of bytes to be read from the file.
Return Value
• This method returns the line read from the file.
Example
f=open('[Link]','w') # creates a new file [Link] give write permissions on file
#writing content into file using write method
[Link](['python is easy\n','python is portable\n','python is comfortable'])
[Link]()
f=open('[Link]','r')
#reading first line of the file using readline() method
print([Link]())
The readlines () Method
Python file method readlines() reads until EOF using readline() and returns a list
containing the lines. If the optional sizehint argument is present, instead of reading up to EOF,
whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal
buffer size) are read.
An empty string is returned only when EOF is encountered immediately.
Syntax: [Link]( sizehint )
Parameters
• sizehint − This is the number of bytes to be read from the file.
Return Value
This method returns a list containing the lines.
Example
f=open('[Link]','w') # creates a new file [Link] give write permissions on file
#writing content into file using write method
[Link](['python is easy\n','python is portable\n','python is comfortable'])
[Link]()
f=open('[Link]','r')
#reading all the line of the file using readlines() method
print([Link]())
Manipulating file pointer using seek():
tell (): The tell () method tells you the current position within the file
Syntax: file_object.tell()
Example:
# Open a file
fo = open("[Link]", "r+")
str = [Link](10)
print("Read String is : ", str)
# Check current position
position = [Link]()
print("Current file position : ", position)
[Link]()
Seek (): The seek (offset, from_what) method changes the current file position.
Syntax: [Link](offset, from_what) #where f is file pointer
Parameters:
Offset: Number of postions to move forward
from_what: It defines point of reference.
Returns: Does not return any value
The reference point is selected by the from_what argument. It accepts three values:
• 0: sets the reference point at the beginning of the file
• 1: sets the reference point at the current file position
• 2: sets the reference point at the end of the file
By default from_what argument is set to 0.
Note: Reference point at current position / end of file cannot be set in text mode except
when offset is equal to 0.
Example:
# Open a file
fo = open("[Link]", "r+")
str = [Link](10)
print("Read String is : ", str)
# Check current position
position = [Link]()
print("Current file position : ", position)
# Reposition pointer at the beginning once again
position = [Link](0, 0);
str = [Link](10)
print("Again read String is : ", str)
# Close opend file
[Link]()
File processing operations:
Python os module provides methods that help you perform file-processing operations,
such as renaming and deleting files.
To use this module you need to import it first and then you can call any related functions.
[Link](): The rename() method takes two arguments, the current filename and the new
filename.(to rename file)
Syntax: [Link](current_file_name, new_file_name)
Example:
import os
[Link](‘[Link]’,’[Link]’) # Creates python named directory
[Link](): The mkdir() method takes one argument as directory name, that you want to
create.(This method is used to create directory)
Syntax: [Link](directory name)
Example:
import os
[Link](‘python’) # Creates python named directory
[Link](): The rmdir() method takes one argument as directory name, that you want to
remove.( This method is used to remove directory)
Syntax: [Link](directory name)
Example:
import os
[Link](‘python’) # removes python named directory
[Link](): The chdir() method takes one argument as directory name which we want to
change.( This method is used to change directory)
Syntax: [Link](newdir)
Example:
import os
[Link](‘D:\>’) # change directory to D drive
[Link](): The remove() method takes one argument, the filename that you want to
remove.( This method is used to remove file)
Syntax: [Link](filename)
Example:
import os
[Link](‘python,txt’) # removes [Link] named file
[Link](): The getcwd() method takes zero arguments,it gives current working director.
Syntax: [Link]()
Example:
import os
[Link]( ) # it gives current working directory
WRITING AND READING CONFIG FILES IN PYTHON
Config files help creating the initial settings for any project, they help avoiding the
hardcoded data. For example, imagine if you migrate your server to a new host and suddenly
your application stops working, now you have to go through your code and search/replace IP
address of host at all the places. Config file comes to the rescue in such situation. You define
the IP address key in config file and use it throughout your code. Later when you want to
change any attribute, just change it in the config file. So this is the use of config file.
Creating and writing config file in Python
In Python we have configparser module which can help us with creation of config files (.ini
format).
Program:
from configparser import ConfigParser
#Get the configparser object
config_object = ConfigParser()
#Assume we need 2 sections in the config file, let's call them USERINFO and
SERVERCONFIG
config_object["USERINFO"] = {
"admin": "Chankey Pathak",
"loginid": "chankeypathak",
"password": "tutswiki"
config_object["SERVERCONFIG"] = {
"host": "[Link]",
"port": "8080",
"ipaddr": "[Link]"
}
#Write the above sections to [Link] file
with open('[Link]', 'w') as conf:
config_object.write(conf)
Now if you check the working directory, you will notice [Link] file has been created, below
is its content.
[USERINFO]
admin = Chankey Pathak
password = tutswiki
loginid = chankeypathak
[SERVERCONFIG]
host = [Link]
ipaddr = [Link]
port = 8080
Reading a key from config file:
So we have created a config file, now in your code you have to read the configuration
data so that you can use it by “keyname” to avoid hardcoded data, let’s see how to do that
Program:
from configparser import ConfigParser
#Read [Link] file
config_object = ConfigParser()
config_object.read("[Link]")
#Get the password
userinfo = config_object["USERINFO"]
print("Password is {}".format(userinfo["password"]))
output:
Password is tutswiki