PP_UNIT-4(PART-1)
PP_UNIT-4(PART-1)
PP_UNIT-4(PART-1)
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.
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).
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.
1 file.closed
Returns true if file is closed, false otherwise.
2 file.mode
Returns access mode with which file was opened.
3 file.name
Returns name of the file.
Example:
f.close()
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: fileObject.close()
Example:
f.close()
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.
• 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: fileObject.write(string)
Here, passed parameter is the content to be written into the opened file.
Example:
f.close()
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: fileObject.writelines(sequence)
Parameters
Example
f.close()
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: fileObject.read([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.close()
f=open('sample.txt','r')
print(f.read(20))
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.
Return Value
Example
f.close()
f=open('sample.txt','r')
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.
Return Value
f.close()
f=open('sample.txt','r')
print(f.readlines())
tell (): The tell () method tells you the current position within the file
Syntax: file_object.tell()
Example:
# Open a file
fo = open("sample.txt", "r+")
str = fo.read(10)
position = fo.tell()
fo.close()
Seek (): The seek (offset, from_what) method changes the current file position.
Syntax: f.seek(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("sample.txt", "r+")
str = fo.read(10)
print("Read String is : ", str)
position = fo.tell()
str = fo.read(10)
fo.close()
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.
os.rename(): The rename() method takes two arguments, the current filename and the new
filename.(to rename file)
Example:
import os
os.mkdir(): The mkdir() method takes one argument as directory name, that you want to
create.(This method is used to create directory)
import os
os.rmdir(): The rmdir() method takes one argument as directory name, that you want to
remove.( This method is used to remove directory)
Example:
import os
os.chdir(): The chdir() method takes one argument as directory name which we want to
change.( This method is used to change directory)
Syntax: os.chdir(newdir)
Example:
import os
os.remove(): The remove() method takes one argument, the filename that you want to
remove.( This method is used to remove file)
Syntax: os.remove(filename)
Example:
import os
os.getcwd(): The getcwd() method takes zero arguments,it gives current working director.
Syntax: os.getcwd()
Example:
import os
os.getcwd( ) # it gives current working directory
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.
In Python we have configparser module which can help us with creation of config files (.ini
format).
Program:
config_object = ConfigParser()
#Assume we need 2 sections in the config file, let's call them USERINFO and
SERVERCONFIG
config_object["USERINFO"] = {
"loginid": "chankeypathak",
"password": "tutswiki"
config_object["SERVERCONFIG"] = {
"host": "tutswiki.com",
"port": "8080",
"ipaddr": "8.8.8.8"
}
config_object.write(conf)
Now if you check the working directory, you will notice config.ini file has been created, below
is its content.
[USERINFO]
password = tutswiki
loginid = chankeypathak
[SERVERCONFIG]
host = tutswiki.com
ipaddr = 8.8.8.8
port = 8080
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:
config_object = ConfigParser()
config_object.read("config.ini")
print("Password is {}".format(userinfo["password"]))
output:
Password is tutswiki