Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
387 views

Python 2 Techmax

python programming-II
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
387 views

Python 2 Techmax

python programming-II
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

PROGRAMMING

WITH PYTHON – II
(As per the Syllabus 2016 - 17 of Mumbai University for FYB.Sc. – CS, Semester II)

Kiran Gurbani
B.E., MCA, M.Phil.,
Head of Computer Science Department,
R.K. Talreja College,
Ulhasnagar - 3.

Vijay Vastava
MCA,
Professor of Computer Science Department and Information Technology,
K.M. Agrawal College of Arts, Science & Commerce,
Kalyan.

ISO 9001:2008 CERTIFIED


© Authors
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any
means, electronic, mechanical, photocopying, recording and/or otherwise without the prior written permission of
the publisher.

First Edition : 2017

Published by : Mrs. Meena Pandey for Himalaya Publishing House Pvt. Ltd.,
“Ramdoot”, Dr. Bhalerao Marg, Girgaon, Mumbai - 400 004.
Phone: 022-23860170, 23863863; Fax: 022-23877178
E-mail: himpub@vsnl.com; Website: www.himpub.com
Branch Offices :
New Delhi : “Pooja Apartments”, 4-B, Murari Lal Street, Ansari Road, Darya Ganj,
New Delhi - 110 002. Phone: 011-23270392, 23278631; Fax: 011-23256286
Nagpur : Kundanlal Chandak Industrial Estate, Ghat Road, Nagpur - 440 018.
Phone: 0712-2738731, 3296733; Telefax: 0712-2721216
Bengaluru : Plot No. 91-33, 2nd Main Road Seshadripuram, Behind Nataraja Theatre,
Bengaluru - 560020. Phone: 08041138821; Mobile: 09379847017, 09379847005.
Hyderabad : No. 3-4-184, Lingampally, Besides Raghavendra Swamy Matham, Kachiguda,
Hyderabad - 500 027. Phone: 040-27560041, 27550139
Chennai : New No. 48/2, Old No. 28/2, Ground Floor, Sarangapani Street, T. Nagar,
Chennai - 600 012. Mobile: 09380460419
Pune : First Floor, "Laksha" Apartment, No. 527, Mehunpura, Shaniwarpeth
(Near Prabhat Theatre), Pune - 411 030.
Phone: 020-24496323/24496333; Mobile: 09370579333
Lucknow : House No 731, Shekhupura Colony, Near B.D. Convent School, Aliganj,
Lucknow - 226 022. Phone: 0522-4012353; Mobile: 09307501549
Ahmedabad : 114, “SHAIL”, 1st Floor, Opp. Madhu Sudan House, C.G. Road, Navrang Pura,
Ahmedabad - 380 009. Phone: 079-26560126; Mobile: 09377088847
Ernakulam : 39/176 (New No. 60/251), 1st Floor, Karikkamuri Road, Ernakulam,
Kochi - 682011. Phone: 0484-2378012, 2378016; Mobile: 09387122121
Bhubaneswar : 5 Station Square, Bhubaneswar - 751 001 (Odisha).
Phone: 0674-2532129; Mobile: 09338746007
Kolkata : 108/4, Beliaghata Main Road, Near ID Hospital, Opp. SBI Bank,
Kolkata - 700 010. Phone: 033-32449649; Mobile: 07439040301
DTP by : Nilima Jadhav
Printed at : M/s. Aditya Offset Process (I) Pvt. Ltd., Hyderabad. On behalf of HPH.
 Dedication 
“Behind every young child who believe in herself is a parent who believe first.” So, I
would like to dedicate this book to my mother and father Kavita S. Bajaj and
Sahijram Bajaj. I would like to thank my son Chirag Gurbani for being my stress
buster and a motivating force for putting a better performance every time.
My sincerest big thanks for a lifetime to Mr. S.K. Srivastava of Himalaya
publication for giving me best writing advice and motivation. His impressive career
advancement inspired me to climb more and more success ladder in my life.

Kiran Gurbani

I would like to dedicate this book to My father Late Shri Laxman B. Vastava and
My Mother Smt Kasturi L. Vastava.

Vijay Vastava
PREFACE
It is a great pleasure in presenting First Edition of this book “Programming with Python – II” to
the students of F.Y.C.S. (FYBSc. Computer Science). This book is written to cover all the topics of
syllabus prescribed by the University of Mumbai for F.Y.B.Sc. C.S.
Python is a widely used high-level programming language used for general-purpose
programming, created by Guido van Rossum and first released in 1991. Python has a design
philosophy which emphasizes code readability (notably using whitespace indentation to delimit code
blocks rather than curly braces or keywords), and a syntax which allows programmers to express
concepts in fewer lines of code than possible in languages such as C++ or Java.
Python is an interpreted, object-oriented, high-level programming language with dynamic
semantics. Its high-level built-in data structures, combined with dynamic typing and dynamic binding,
make it very attractive for Rapid Application Development, as well as for use as a scripting or glue
language to connect existing components together.
Python supports modules and packages, which encourages program modularity and code reuse.
The Python interpreter and the extensive standard library are available in source or binary form
without charge for all major platforms, and can be freely distributed.
Python 2.0 was released on 16 October 2000 and had many major new features.
Python 3.0 (which early in its development was commonly referred to as Python 3000 or py3k).
I recommend this book as a Programmer’s point of view. This book teaches Advance Python
starting with the file handling, Exception handling with Regular Expression and GUI Programming
along with Database Connectivity with MySQL and Sqlite3 and Networking.
This book offers you a comprehensive learning tool for Python. It covers almost everything you
need to know about programming in Python: Types and Operations, Statements and Syntax,
Functions and Iterators, Generators, Modules and Packages, Databases and much more.
Here, in this book, the concept of each topic is followed by the theoretical explanation, all
practical questions of Python programming with MCQ (Multiple Choice questions) according to
university pattern are provided at the end of this book, and along with those steps of program
execution is provided. Efforts have been made to make the text easy to read and understand. In this
book, we have covered all types of programs expected by University of Mumbai in practical
examination.
Constructive suggestion and comments from the users will be sincerely appreciated. We would
appreciate hearing from you about any textual errors or omissions which you identify. If you would
like to suggest improvements or to contribute in any way, we would be glad to hear from you.
Please send correspondence to kiranrktcollege@gmail.com and vvastava@gmail.com.
Last but not the least, we would like to give big lifetime thanks to Mr. S.K. Srivastava
(Himalaya Publishing House) for providing an environment which stimulates new thinking and
innovations and his support, motivation, guidance, cooperation and encouragement to write this book.
We are grateful for his support and thank him for his true blessings.

Kiran Gurbani Vijay Vastava


kiranrktcollege@gmail.com vvastava@gmail.com
9637128628/7769979964 9594950917
SYLLABUS
Programming with Python – II
Semester II – Theory
(Credits: 2 Lectures/Week: 3)
Course: USCS202
Objectives:
The objective of this paper is to explore the style of structured programming to give the idea to the
students how programming can be used for designing real-life applications by reading/writing to file, GUI
programming, interfacing database/networks and various other features.
Expected Learning Outcomes
1. Students should be able to understand how to read/write to files using Python.
2. Students should be able to catch their own errors that happen during execution of programs.
3. Students should get an introduction to the concept of pattern matching.
4. Students should be made familiar with the concepts of GUI controls and designing GUI
applications.
5. Students should be able to connect to the database to move the data to/from the application.
6. Students should know how to connect to computers, read from URL and send email.

Unit I Python File Input-Output: Opening and closing file, various types of file modes, 15 L
reading and writing to files, manipulating directories.
Iterables, iterators and their problem solving applications.
Exception Handling: What is an exception? various keywords to handle exceptions
such as try, catch, except, else finally, raise.
Regular Expressions: Concept of regular expression, various types of regular
expressions, using match function.
Unit II GUI Programming in Python (using Tkinter/WxPython/Qt): 15 L
What is GUI? Advantages of GUI, Introduction to GUI library. Layout management.
events and bindings, fonts, colours, drawing on canvas on canvas (line, oval,
ractangle, etc.)
Widgets such as: framem label, button, checkbutton, entry, listbox, message,
radiobutton, text, spinbox etc.
Unit III Database Connectivity in Python: Installing My SQL connector, accessing 15 L
connector module module, using connect, cursor, execute and close functions,
reading single and multiple results of query execution, executing different types of
statements, executing transactions, understanding exceptions in database
conncectivity.
Network Connectivity: Socket module, creating server-client programs sending
email, reading from URL
Text Books:
1. Paul Gries, Jennifer Campbell and Jason Montoja, Practical Programming: An Introduction to
Computer Science using Python 3, Pragmatic Bookshell, 2/E 2014.
Additional References:
1. James Payne, Beginning Python: Using Python 2.6 and Python 3, Wiley India, 2010.
2. A. Lukaszewski, My SQL for Python: Database Access Made Easy, Pact Publisher, 2010.

Semester II – Practical
Practical of USCS201 + USCS202 + USCS203 + USCS204 + USCS205 + USCS206
(Credits: 6, Lectures/Week: 18)
Course: USCSP2

USCSP202 Programming with Python – II


1. Programs to read and write files.
2. Programs with iterables and iterators.
3. Program to demonstrate exception handling.
4. Program to demonstrate the use of regular expressions.
5. Program to show draw shapes and GUI controls.
6. Program to create server-client and exchange basic information.
7. Programs to send email and read contents of URL
PAPER PATTERN
Max. Marks : 75 Time : 2 1/2 Hrs.
All Questions are compulsory.

Q. 1 Covering All the Units(I, II and III)


Attempt all (Each of 5 Marks) 15 Marks
(a) Multiple Choice Questions …….. 5 Marks
(b) Fill in the Blanks …….. 5 Marks
(c) Short Notes …….. 5 Marks
Q. 2 From Unit I (With 100% Option)
Attempt any three of following 15 Marks
(a) …….. 5 Marks
(b) …….. 5 Marks
(c) …….. 5 Marks
(d) …….. 5 Marks
(e) …….. 5 Marks
(f) …….. 5 Marks
Q. 3 From Unit II (With 100% Option)
Attempt any three of following 15 Marks
(a) …….. 5 Marks
(b) …….. 5 Marks
(c) …….. 5 Marks
(d) …….. 5 Marks
(e) …….. 5 Marks
(f) …….. 5 Marks
Q. 4 From Unit III (With 100% Option)
Attempt any three of following 15 Marks
(a) …….. 5Marks
(b) …….. 5 Marks
(c) …….. 5 Marks
(d) …….. 5 Marks
(e) …….. 5 Marks
(f) …….. 5 Marks
Q. 5 Covering All the Units (I, II and III) with 75% Option
Attempt any three of following 15 Marks
(a) …….. 5 Marks
(b) …….. 5 Marks
(c) …….. 5 Marks
(d) …….. 5 Marks
(e) …….. 5 Marks
(f) …….. 5 Marks
CONTENTS

UNIT I

1 PYTHON FILE INPUT-OUTPUT 1 – 39

2 EXCEPTION HANDLING 40 – 62

3 REGULAR EXPRESSION 63 – 80

UNIT II

4 GUI PROGRAMMING IN PYTHON 81 – 114

UNIT III

5 DATABASE CONNECTIVITY IN PYTHON 115 – 162

6 NETWORK CONNECTIVITY 163 – 202

FINAL PYTHON PRACTICALS 203 – 244

PYTHON PROGRAMMING MCQ 245 – 250

MODEL QUESTIONS 251 – 252


Unit I

Chapter 1
Python File
Input-Output

Structure
1.1 Introduction to File Handling
1.1.1 Text File
1.1.2 Binary File
1.1.3 Differentiate between Text File and Binary File
1.1.4 File operations
1.2 Opening and Closing Files
1.2.1 Opening File by using Open( )
1.2.1.1 Open For Reading
1.2.1.2 Opening for Writing
1.3 Closing File by Using Close( )
1.3.1 Various Types ofFile Modes
1.3.2 Attributes of File Object
1.4 Reading and Writing to Files
1.4.1 Reading File through Read( ) and Readline( ) and readlines( )
1.4.2 Reading Input from Keyboard
1.4.3 Writing File through Write( )
1.5 Appending Text to a File
1.6 Renaming a File
1.7 Deleting a File
1.8 Python Different file Input Output Functions
1.9 File Positions
1.10 Manipulating Directories
1.10.1 Directories in Python
1.10.2 mkdir( ) Method
2 Programming with Python – II
1.10.3 chdir( ) Method
1.10.4 getcwd( ) Method
1.10.5 rmdir( ) Method
1.11 Python Iterators and Iterables
1.11.1 Python Iterators
1.11.2 Python Iterables
1.11.3 Creating Your Own Iterator in Python
1.11.4 Python Infinite Iterators
1.11.5 Generators
1.12 Iterations and their Problem Solving Applications
1.13 Questions

1.1 Introduction to File Handling


In Python programming, File is a named location on disk to store related information. It is used
to permanently store data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when computer is turned
off, we use files for future use of the data.
File is of text file, music File or binary file or video file, All these files are categorized into two
types
1. Text File
2. Binay File
When we want to read from or write to a file we need to open it first. When we are done, it needs
to be closed, so that resources that are tied with the file are freed

Why files are needed?


► When a program is terminated, the entire data is lost. Storing in a file will preserve your data
even if the program terminates.
► If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the
file using few commands in C.
► You can easily move your data from one computer to another without any changes.
File Handling concept in python language is used for store a data permanently in computer
memory. Using this concept we can store our data in Secondary memory (Hard disk). A file represents
a sequence of bytes on the disk where a group of related data is stored. File is created for permanent
storage of data. It uses file object to process file.

1.1.1 Text File


A text file is often structures as a sequence of lines and a line is a sequence of characters. The
line is terminated by EOL (End of Line) character.
Python File Input-Output 3

A text file is a file containing characters, structured as individual lines of text. In addition to
printable characters, text files also contain the nonprinting newline character, \n, to denote the end of
each text line. The newline character causes the screen cursor to move to the beginning of the next
screen line. Thus, text files can be directly viewed and created using a text editor.

1.1.2 Binary File


Binary files can contain various types of data, such as numerical values, and are therefore not
structured as lines of text. Such files can only be read and written via a computer program.
Any attempt to directly view a binary file will result in “garbled” characters on the screen. A
binary file is a file that is formatted in a way that only a computer program can read.

1.1.3 Differentiate between Text File and Binary File


Text File Binary File
A text file is often structures as a sequence of lines Binary files can contain various types of data,
and a line is a sequence of characters. The line is such as numerical values, and are therefore not
terminated by EOL (End of Line) character. structured as lines of text
Text files contain ASCII codes of digits, Binary file contains collection of bytes (0’s and
alphabetic and symbols 1’s). Binary files are compiled version of text files.
A text file is a file containing characters, A binary file is a file that is
structured as individual lines of text. formatted in a way that only a computer program
can read.
File Access modes for Text file are File Access modes for Binary file are
r → opens a file for reading only rb → opens a file for reading only
r+ → opens file for both reading and writing rb+ → opens file for both reading and writing
w → opens file for writing only wb → opens file for writing only
w+ → opens file for writing and reading wb+ → opens file for writing and reading
a → opens file for appending ab → opens file for appending
a+ → opens file for appending and reading ab+ → opens file for appending and reading

1.1.4 File Operations


Different File operations can be performed as follows :-
1. Creation of new file
open( ) with “w” attribute
2. Opening an Existing File
open( ) with “w” or “r” or “a” attribute
3. Reading Data from file
read( ) or readline( ) and readlines( )
4. Writing data into file
write( )
5. Appending Data into file
open( ) with “a” attribute
4 Programming with Python – II
6. Closing a file
Close( )
All files must first be opened before they can be used. In Python, when a file is opened, a file
object is created that provides methods for accessing the file.

1.2 Opening and Closing Text Files


We are reading and writing to the standard input and output till now but next we will see how to
play with actual data files.
Python provides basic functions and methods necessary to manipulate files by default. You can
do your most of the file manipulation using a file object.
For opening and closing a file respectively open( ) and close( ) method is used.

1.2.1 Opening of File Using Open( )


The open Function
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(file_name [, access_mode][, buffering])
Here is paramters' detail
► 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 of
section 1.3. This is optional parameter and the default file access mode is read (r).
► buffering: If the buffering value is set to 0, no buffering will take place. If the buffering value
is 1, line buffering will be performed while accessing a file. If you specify the buffering value
as an integer greater than 1, then buffering action will be performed with the indicated buffer
size. If negative, the buffer size is the system default(default behavior).
Example
# Open a file in write mode
>>> fobj=open( “kiran.txt”,”w”)
Where fobj is a File object, open is a python function with specified file name and mode of
penning a file. Open function returns file object.
# Other way to Open a file in write mode by using with Keyword
>>> with open( “kiran.txt”,”w”) as fobj:
Where fobj is a File object, open is a python function with specified file name and mode of
penning a file. Open function returns file object.
Python File Input-Output 5

Here is a list of the Basic three different modes of opening a file:

Modes Description

r Opens a file for reading only. The file pointer is placed at the beginning of the file. This
is the default mode.

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.

a Opens a 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.

All files must first be opened before they can be read from or written to.
Example of open method

#!/usr/bin/python
# Open a file

fobj = open("kiran.txt", "w")


print ("Name of the file: ", fobj.name)

# Close opened file


fobj.close()
Output
Name of the file: kiran.txt
In this Example with the help of open( ) method, kiran.txt file is opened for writing indicated by
w, With the help of name attribute of file object we can get confirmation name of the file which is
opened. With the help of close( ) method we are closing file object in turn file is closed and
inaccessible.
1.2.1.1 Opening for Reading
To open a file for reading, the built-in open function is used as shown,
input_fileobj = open ('kiranfile.txt','r')
input_fileobj is a object, The first argument is the file name to be opened, 'kiranfile.txt'.
The second argument, 'r', indicates that the file is to be opened for reading. (The second argument is
optional when opening a file)
In Python, when a file is (successfully) opened, a file object is created that provides methods for
accessing the file. If the file is successfully opened, a file object is created and assigned to the
provided identifier, in this case identifier input_fileobj.
6 Programming with Python – II
When opening a file for reading, if the file name does not exist, then the program will terminate
with a “no such fi le or directory” error.
When a file is opened, it is first searched for in the same folder/directory that the program resides in.
There are two methods to specify path
1. Relative path
2. Absolute path
1. Relative path: Alternate location can be specified in the call to open by providing a path to
the file,
input_fileobj = open('kiran/kiranfile.txt','r')
Here the file is searched for in a subdirectory called kiran of the directory in which the
program is contained. Thus, its location is relative to the program location. Directory paths in
Python are always written with forward slashes.
2. Absolute path: Absolute paths can also be provided giving the location of a file anywhere in
the file system,
input_fi leobj = open('C:/mypythonfiles/kiran/kiranfile.txt','r').
When the program has finished reading the file, it should be closed by calling the close
method on the file object.
input_fi leobj.close()
Once closed, the file may be reopened (with reading starting at the beginning of the file) by
the same, or another program.
Example for open for Reading
fo=open("foo.txt","r+")
str=fo.read(10)
print ("read string is",str)
fo.close()
Output
read string is python in
Python File Input-Output 7

1.2.1.2 Opening for Writing


To open a file for writing, the open function is used as shown below
output_fileobj = open('kiranfile.txt','w')
In this case, 'w' is used to indicate that the file is to be opened for writing. If the file already exists,
it will be overwritten (starting with the first line of the file). When using a second argument of 'a', the
output will be appended to an existing file instead.
It is important to close a file that is written to, otherwise the tail end of the file may not be written
to the file.
output_file.close()
When opening files for writing, there is not much chance of an I/O error occurring. The provided
file name does not need to exist since it is being created (or overwritten). Thus, the only error that may
occur is if the file system (such as the hard disk) is full.
w mode can be used for text file
wb mode can be used for binary file
Example for open for Writing in Binary Mode
fo=open("foo.txt","wb")
fo.write("python in great lang\n")
fo.close
Output
>>> ================================ RESTART
================================
>>>
8 Programming with Python – II

1.2.2 Closing of File Using Close( )


The Close() Method
The close() method of a file object flushes any unwritten information and closes the file object,
once the file is closed no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file.
It is a good practice to use the close() method to close a file.
Syntax
fileobject.close( )
Example to Show Demo of Close Function
fo=open("foo.txt","wb")
print ("name of the file",fo.name)
fo.close
Output
name of the file foo.txt
Python File Input-Output 9

1.3 Various Types of File Modes


Here is a list of the different modes of opening a file:

Modes Description

r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is
the default mode.

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.

r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file.

rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the
beginning of the file.

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.

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.

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.

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.

a Opens a 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.

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.
10 Programming with Python – II

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.

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.

Once file is opened and you have one file object, Here is a list of all attributes related to file object.

1.3 Attributes of File Object


Attribute Description

file.closed Returns true if file is closed, false otherwise.

file.mode Returns access mode with which file was opened. (i.e., ‘r’, ‘w’, ‘r+,’rb’, etc.)

file.name Returns name of the file.

file.softspace Returns false if space explicitly required with print, true otherwise.

>>> my_file.closed
False
>>> my_file.mode
'r'
>>> my_file.name
'mynewfile.txt'
Example: Write a program in GUI to show opening and closing file.
Program
fo=open("foo.txt","wb")
print"name of file:",fo.name
print"closed or not:",fo.closed
print"opening mode:",fo.mode
print"softspace flag:",fo.softspace
Output
name of file: foo.txt
closed or not: False
Python File Input-Output 11

opening mode: wb
softspace flag: 0

1.4 Reading and Writing to Files


1. The file object provides a set of access methods to make use of files easier to access. read( )
and write( ) methods to read and write files.
2. As already stated there are two types of files are available, text file and Binary File
3. Text file consist of sequence of characters terminated by End of Line (EOL) character is used
to terminate the line.

1.4.1 Reading File through Read( ) and Readline( ) and Readlines( )


1. Reading from a file is similar. First, open the file by creating a file object. This time, use
“ r ” to tell Python you intend to read from the file. Specify filename in first argument & can
omit the second argument.
a=open(“kiran.txt”,”r”)
use the path of the text file same as where you are writing program, If file exist Python read
the file and if the file doesn ’t exist, Python will raise an exception.
You can read a line from the file using the readline method. The first time you call this
method on a file object, it will return the first line of text in the file:
> > > a.readline()
read( ) and readline( ) these two methods are used to read the contents of the file.
2. readline( ) includes the newline character at the end of the string it returns. To read the
contents of the file one line at a time, call readline( ) method repeatedly.
3. read( ) Method can also read the rest of the file all at once. This method returns any text in
the file that you haven ’t read yet. (If you call read as soon as you open a file, it will return
the entire contents of the file, as one long string)
12 Programming with Python – II
> > > f=open(“test.txt”,”r”)
> > > text=a.read()
> > > print(text)
This will read all contents of file & print it on standard output.
4. readline( ) method returns as a string the next line of a text fi le, including the end-of-line
character, \n. When the end-of-fi le is reached, it returns an empty string as demonstrated in
the while loop of Figure 1.4.
Since we are creating Text File kiran.txt
Text File kiran.txt Screen Output

Hello
Hello\n input_fileobj =
How are You\n open(‘kiran.txt’,’r’)
How are You
Welcome to Python str=’ ’
Learning\n line = input_fileobj.readline( ) Welcome to Python
while line != str: Learning
print(line)
line=
input_fileobj.readline( )
input_fileobj.close( )

Fig 1.4: Reading of a file through readline( ) Method


5. For reading all lines from the file either we can use for loop or while loop,
6. In for loop all lines of the file will be read one by one and by using a while loop lines can be
read until a given value is found, Finally, note the blank lines in the screen output. Since
readline( ) method returns the newline character, and print adds a newline character, two
newline characters are output for each line displayed, resulting in a skipped line after each.
7. readlines( )
The 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
Following is the syntax for readlines( ) method −
fileObject.readlines( sizehint );
sizehint argument -- This is the number of bytes to be read from the file.
When you create a file object in Python you can read from it in several different ways. Not until
today did I understand the difference between readline() and readlines(). The answer is in the name.
readline() reads one line character at a time, readlines() reads in the whole file at once and splits it by line.
Python File Input-Output 13

These would then be equivalent:


f = open('somefile.txt','r')
for line in f.readlines():
print (line)
f.close()

# ...and...
f = open('somefile.txt','r')
for line in f.read().split('\n'):
print (line)
f.close()

1.4.2 Reading Keyboard Input


Python provides two built-in functions to read a line of text from standard input, which by default
comes from the keyboard. These functions are:
► raw_input
► input
Python provides two built-in functions to read a line of text from standard input, which by default
comes from the keyboard. These functions are −
► raw_input
► input
The raw_input Function
The raw_input([prompt]) function reads one line from standard input and returns it as a string
(removing the trailing newline).
#!/usr/bin/python
str = raw_input("Enter your input: ");
print "Received input is : ", str
This prompts you to enter any string and it would display same string on the screen. When I
typed "Hello Python!", its output is like this −
Enter your input: Hello Python
Received input is : Hello Python
Example: GUI to print raw_input function.
Program:
str=raw_input("enter your input");
print"received input is:",str
14 Programming with Python – II
Output:
enter your input :hello python
received input is: hello python

The Input Function


The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a
valid Python expression and returns the evaluated result to you.
#!/usr/bin/python
str = input("Enter your input: ");
print "Received input is : ", str
This would produce the following result against the entered input −
Enter your input: [x*5 for x in range(2,10,2)]
Received input is : [10, 20, 30, 40]

Example in GUI to print input function


Program:
str=input("enter your input:");
print"received input is:",str
Output
enter your input:[x*5 for x in range (2,10,2)]
received input is: [10, 20, 30, 40]
Python File Input-Output 15

1.4.3 Writing File through Write( )


1. Writing into a file is similar. Start by creating a file with some simple text. To create a new
file on your system, Then, open the file by creating a file object. This time, use “ w ” to tell
Python you intend to write into the file. Specify filename in first argument & can omit the
second argument.
a=open(“kiran.txt”,”w”)
2. write( ) method writes any string to an open file. It is important to note that Python strings
can have binary data and not just text.
3. The write() method does not add a newline character ('\n') to the end of the string:
Enter the following:
> > > def make_text_file():
a=open(‘kiran.txt’,”w”)
a.write(“This is how you create a new text file”)
a.close()
make_text_file() inbuilt function used to create text file. With the help of file object a , file
can be opened for writing named as kiran.txt. The “w” argument tells Python that you intend
to write to the file and with the help of write( ) method writing line into a file.
The write() method does not add a newline character ('\n') to the end of the string:
Now open a kira.txt file in write mode & then write two lines using multiple write( ) method
> > > def make_text_file():
a=open(‘kiran.txt’,”w”)
a.write(“This is how you create a new text file”)
a.write(“This is how add more lines to text file”)
a.close()
16 Programming with Python – II
make_text_file() inbuilt function used to create text file. With the help of file object a , file
can be opened for writing named as kiran.txt. The “ w ” argument tells Python that you
intend to write to the file and with the help of write( ) method more than one time writing
multiple lines into a file.
4. Now that you have created a file with the preceding technique, create a program that first
checks to see if the file name exists; if so, it will give you an error message; if not, it will
create the file.
Type in the following code:
> > > import os
> > > def make_another_file():
if os.path.isfile(‘kiran.txt’):
print(“You are trying to create a file that already exists!”)
else:
f=open(‘kiran.txt’,”w”)
f.write(“This is how you create a new text file”)
...
> > > make_another_file()
”You are trying to create a file that already exists! ”
Syntax
file Object.write(string);
Here, passed parameter is the content to be written into the opened file.
Example
#! /usr/bin/python

# Open a file
fo # open (“foo.txt”, “wb”)

fo. Write (“Python is a great language. \nYeah its great ! ! \n”);

# Close opened file


fo. Close ()
The above method would create foo.txt file and would write given content in that file and finally
it would close that file. If you would open this file, it would have following content:
Python is a great language.
Yeah its great! !
Python File Input-Output 17

1.5 Appending Text to a File


1. Appending text is adding text at the end of the file.
2. Instead of using the write method ( “w” ), you use append instead ( “a” ).
3. In append mode, you ensure that the data in the existing file is not overwritten, but instead,
any new text is appended to the end of the file.
4. When file is opened in append mode, the cursor by default places at the EOL of the file &
new text will be added at the end of the file.
Example of Appending Text to a File
> > > def add_some_text():
fobj=open(‘kiran.txt’,”r”)
text=fobj.read( )
print(“\n”,text)
fobj.close( )
fobj=open(‘kiran.txt’,”a”)
fobj.write(“\n Here is some additional text!”)
text = f.read( )
print(“\n”, text)
Run the Module & observe the output
> > > add_some_text()
My name is kiran
This book is written for Fycs students
My name is kiran
This book is written for Fycs students
Here is some additional text!
In the example,
1. I created a function called add_some_text().
2. open method to open file, kiran.txt in read mode
3. with the read method reading whole contents of the file & storing into text object
4. print text object contents with the help of print method
5. closing file object
6. Again open the file in append mode
7. Adding & writing a line at the end of the file, telling Python you wanted to append to your file
(this is the “ a ” argument).
8. with the read method reading whole contents of the file & storing into text object
18 Programming with Python – II
9. print text object contents with the help of print method
10. closing file object

1.6 Renaming a File


1. When we want to change name of the File then we can use rename( ) method of python
2. The OS Module of Python provides different methods for file-processing operations, from
that one of the function rename( ) is provided to change name of the file.
3. If we want to use rename( ) method, we have to import OS Module. After importing OS
Module, we can use all file processing operation functions.
Syntax of rename() Method:
os.rename(current_file_name, new_file_name)
The rename() method takes two arguments, the current filename and the new filename.
Example
Following is the example to rename an existing file kiran.txt:

#!/usr/bin/python
import os
# Rename a file from kiran.txt to ks.txt
os.rename( "kiran.txt", "ks.txt" )

Hence kiran.txt file renamed with ks.txt

1.7 Deleting a File


1. When we want to delete File then we can use remove( ) method of python
2. The OS Module of Python provides different methods for file-processing operations, from
that one of the method remove( ) is provided to delete the file.
3. If we want to use remove( ) method, we have to import OS Module. After importing OS
Module, we can use all file processing operation functions.
Syntax of remove( ) Method:
os.remove(file_name)

You can use the remove() method to delete files by supplying the name of the file to be
deleted as the argument.
Example
Following is the example to delete an existing file ks.txt:
#!/usr/bin/python
import os
Python File Input-Output 19

# Delete file test2.txt


os.remove("ks.txt")

1.8 Python Different File Input Output Functions


1. Python is providing file handling with different file processing operations
2. Python provides OS Module with different file processing operations and methods
3. Python OS Module provides different methods for opening a file in a different modes, reading
and writing into a file & appending new data into a file, renaming , moving, deleting and
closing a file.
4. Python has a rich collection of input output functions, they are listed as below
(a) open( )
(b) read( )
(c) readline( )
(d) write( )
(e) rename( )
(f) remove( )
(g) move( )
(h) close( )
All these methods are explained further in this chapter with description & suitable example

1.9 File Positions


tell( ) and seek( ) methods are used for finding file positions
1. tell( )
The method tell() returns the current position of the file read/write pointer within the file. The
next read or write will occur at that many bytes from the beginning of the file.
Syntax
fileObject.tell()

Return Value
This method returns the current position of the file read/write pointer within the file.
Example
The following example shows the usage of tell() method.
Assume created a new file named as kiran.txt
Python is a great language
Python is also structured language
Python is also object oriented language
Python has tuples
20 Programming with Python – II

Python has Dictionaries


#!/usr/bin/python
# Open a file
fo = open("kiran.txt", "rw+")
print "Name of the file: ", fo.name
line = fo.readline()
print "Read Line: %s" % (line)
# Get the current position of the file.
pos = fo.tell()
print "Current Position: %d" % (pos)
fo.close( ) # Close opend file

Run the program to see result


Name of the file: kiran.txt
Read Line: Python is a great language.

Current Position: 28

Example
Let us take a file kiran.txt, which we created above.
#!/usr/bin/python

# Open a file
fo = open("kiran.txt", "r+")
str = fo.read(10);
print "Read String is : ", str

# Check current position


position = fo.tell();
print "Current file position : ", position

# Reposition pointer at the beginning once again


position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opend file
fo.close()
Python File Input-Output 21

This produces the following result −


Read String is : Python is
Current file position : 10
Again read String is : Python is
2. seek( )
The seek( ) method changes the current file position. When there is a need to change file position
at some specific position, then seek method is used. seek( ) method has two parameters/arguments
Syntax
Following is the syntax forseek() method −
seek(offset[, from])
Parameters
► offset: This is the position of the read/write pointer within the file, This will indicate the
number of bytes to be moved.
► from: It specfies the reference position from where the bytes are to be moved.
This is optional and It has values 0,1,2.
defaults to 0 which means use the beginning of the file as the reference
value 1 which means seek relative to the current position, means use the current position as
the reference position
value 2 means seek relative to the file's end that means end of the file would be taken as the
reference position.
Example
The following example shows the usage of seek() method.
Assume created a new file named as kiran.txt
Python is a great language
Python is also structured language
Python is also object oriented language
Python has tuples

Example
#!/usr/bin/python
# Open a file
fo = open("kiran.txt", "rw+")
print "Name of the file: ", fo.name
line = fo.readline()
print "Read Line: %s" % (line)
# Again set the pointer to the beginning
fo.seek(0, 0)
22 Programming with Python – II
line = fo.readline()
print "Read Line: %s" % (line)

# Close opend file


fo.close()
Run above program and see result
Name of the file: kiran.txt
Read Line: Python is a great language.
Read Line: Python is a great language.

Example in GUI o show the current position and read function.


Program:
fo=open("foo.txt","r+")
str=fo.read(10);
print"read string is:",str
position=fo.tell();
print"current position is:",+position
osition=fo.seek(0,0);
str=fo.read(10);
print"read string is:",str
fo.close()
Output
read string is: python in
current position is: 9
read string is: python in
Python File Input-Output 23

1.10 Manipulating Directories


1.10.1 Directories in Python
► Directory in a python consist of all python files
► Python provides different utility methods to manipulate files & directories
– File Object Methods has different functions to manipulate files. File Object has several
methods to create, open, read, write, flush, make file position and closing of the file.
– OS Object Methods has different functions to process files as well as directories. OS
several methods that help you create, remove, and change directories.
A file object is created using open function and here is a list of functions which can be called
on this object:
Sr. No. Methods with Description
1 file.close() Close the file. A closed file cannot be read or written any more.
2 file.flush() Flush the internal buffer, like stdio's fflush. This may be a no-op on some file-
like objects.
3 file.fileno() Returns the integer file descriptor that is used by the underlying implementation
to request I/O operations from the operating system.
4 file.isatty() Returns True if the file is connected to a tty(-like) device, else False.
5 file.next() Returnss the next line from the file each time it is being called.
6 file.read([size]) Reads at most size bytes from the file (less if the read hits EOF before
obtaining size bytes).
7 file.readline([size]) Reads one entire line from the file. A trailing newline character is kept
in the string.
8 file.readlines([sizehint]) Reads until EOF using readline() and return 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.
9 file.seek(offset[,whence]) Sets the file's current position.
10 file.tell() Returns the file's current position
11 file.truncate([size]) Truncates the file's size. If the optional size argument is present, the file
is truncated to (at most) that size.
12 file.write(str) Writes a string to the file. There is no return value.
13 file.writelines(sequence) Writes a sequence of strings to the file. The sequence can be any
iterable object producing strings, typically a list of strings.

OS Object Methods
This provides methods to process files as well as directories
Sr. No. Methods with Description
1 os.access(path,mode) Use the real uid/gid to test for access to path.
2 os.chdir(path) Change the current working directory to path
3 os.chmod(path, mode) Change the mode of path to the numeric mode.
4 os.chown(path, uid, gid) Change the owner and group id of path to the numeric uid and gid.
5 os.chroot(path) Change the root directory of the current process to path.
24 Programming with Python – II

6 os.close(fd) Close file descriptor fd.


7 os.dup(fd) Return a duplicate of file descriptor fd.
8 os.getcwd() Return a string representing the current working directory.
9 os.link(src, dst) Create a hard link pointing to src named dst.
10 os.listdir(path) Return a list containing the names of the entries in the directory given by
path.
11 os.lseek(fd, pos, how) Set the current position of file descriptor fd to position pos, modified
by how.
12 os.makedirs(path[, mode]) Recursive directory creation function.
13 os.open(file, flags[, mode]) Open the file file and set various flags according to flags and
possibly its mode according to mode.
14 os.read(fd, n) Read at most n bytes from file descriptor fd. Return a string containing the
bytes read. If the end of the file referred to by fd has been reached, an empty string is
returned.
15 os.remove(path) Remove the file path.
16 os.rename(src, dst) Rename the file or directory src to dst.
17 os.rmdir(path) Remove the directory path
18 os.tmpfile() Return a new file object opened in update mode (w+b).
19 os.write(fd, str) Write the string str to file descriptor fd. Return the number of bytes actually
written.

1.10.2 The mkdir( ) Method


► mkdir() stands for make directory
► This method is used to create a new directory in current directory path.
► This method available in OS Module
► mkdir(argument): In mkdir( ) we have to pass one argument which contains the name of
the directory to be created, since mkdir( ) is available in OS Module, hence before creating a
directory, you have to import OS Module.
Syntax
os.mkdir("newdir")

Example
Following is the example to create a directory kiran in the current directory −
#!/usr/bin/python
import os
# Create a directory "test"
os.mkdir("kiran")

1.10.3 The chdir() Method


► chdir() stands for change directory
► This method is used to change current directory path.
Python File Input-Output 25

► This method available in OS Module


► chdir(argument): In chdir( ) we have to pass one argument which contains the name of the
directory to where we have to change, since chdir( ) is available in OS Module, hence before
changing to a directory, you have to import OS Module.
Syntax
os.chdir("kiran")

Example
Following is the example to go into "/home/ks" directory −
#!/usr/bin/python
import os
# This would give location of the current directory
os.getcwd()

1.10.4 The getcwd() Method


► getcwd() stands for get current working directory
► This method is used to display current working directory.
► This method available in OS Module
► since getcwd( ) is available in OS Module, hence before using this function to display current
working directory, you have to import OS Module.
Syntax
os.getcwd()

Example
Following is the example to give current directory −
#!/usr/bin/python
import os
# This would give location of the current directory
os.getcwd()

1.10.5 The rmdir( ) Method


► rmdir() stands for remove directory
► This method is used to remove or delete a directory.
► This method available in OS Module
► rmdir(argument):- In rmdir( ) we have to pass one argument which contains the name of
the directory to be deleted or removed, since rmdir( ) is available in OS Module, hence before
deleting a directory, you have to import OS Module.
26 Programming with Python – II
► Before removing a directory, all the contents in it should be removed, meand directory should
be empty
► Before removing a directory,you should be out of that directory.
Syntax
os.rmdir('dirname')

Example
Following is the example to remove "/home/ks" directory. It is required to give fully qualified
name of the directory, otherwise it would search for that directory in the current directory, only
condition is ks directory should be empty & you should not be in ks directory.
#!/usr/bin/python
import os

# This would remove "/tmp/test" directory.


os.rmdir("/home/ks" )

1.11 Iterators, Iterables


1.11.1 Python Iterators
1. Iterator is an object which allows a programmer to traverse through all the elements of a
collection, regardless of its specific implementation.
2. Iterators are objects that can be iterated upon.
3. Iterator in Python is simply an object that can be iterated upon. An object which will return
data, one element at a time.
4. Python iterator object is based to iterator protocol, while creating iterator object python
must implement two special methods,
(a) __iter__()
(b) __next__(), collectively called the iterator protocol, that means you can build your own
iterator using __iter__ and __next__ methods.
–– The __iter__ returns the iterator object itself. If required, some initialization can
be performed. This is used in for and in statements.
–– The __next__method returns the next value from the iterator means It returns the
next item in the sequence. On reaching the end, it must raise StopIteration.
5. They are implemented within for loops, comprehensions, generators etc.
6. An object is called iterable if we can get an iterator from it. Most of built-in containers in
Python like: list, tuple,string etc. are iterables.
7. Iterator decouples the data from algorithm.

You might also like