Unit 5 - Files and Exceptions
Unit 5 - Files and Exceptions
(AUTONOMOUS)
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND
DATA SCIENCE
Unit V -Notes
I YEAR –B.E/B.TECH
(Common to all Branches)
PREPARED BY APPROVED BY
HOD
UNIT V : FILES, EXCEPTIONS
Files: text files, reading and writing files, format operator, filenames and paths; Exceptions:
handling exceptions, multiple exception blocks, finally block; Case study: tkinter.
FILES:
A file can be defined as a location for storing related data. A file holds a specific
name for itself. A file can be a sequence of bits, bytes, lines or records depending on
the application used to create it.
Example:
sample.py, student.txt –Here sample, student are the file names with file extensions
Need/Advantages/Purpose of Files:
Files are used to store data permanently on a non-volatile memory such as
hard disks, magnetic disks, magnetic tapes, optical disks.
Files can be used for storing useful information or data for future reference,
Files are used to store persistent data
File Path
Files that we use are stored on a storage medium like the hard disk in such a way that
they can be easily retrieved as and when required.
Every file is identified by its path that begins from the root node or the root folder. In
Windows, C:\ (also known as C drive) is the root folder but you can also have a path
that starts from other drives like D:\, E:\, etc. The file path is also known as pathname.
Relative Path and Absolute Path :
A file path can be either relative or absolute. While an absolute path always contains
the root and the complete directory list to specify the exact location the file, relative
path needs to be combined with another path in order to access a file. It starts with
respect to the current working directory and therefore lacks the leading slashes. For
example, C:\Students\Under Graduate\BTech_CS.docx but Under
Graduate\BTech_CS.docx is a relative path as only a part of the complete path is
specified.
Types of files:
Files can be categorized as follows:
Text files:
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
Binary files:
Binary files can contain various types of data, such as numerical values. These
are not structured as lines of text. Such files can only be read and written via a
computer program.
FILE OPERATIONS:
Files in python can be manipulated via the following file operations:
Opening a file
Reading from a file
Writing to a file
Appending a file
Closing a file
Opening a file
All files must be opened first before they can be used. In python, when a file is
opened, a file object is created that provides methods for accessing the file. In python
there is a built in function open() to open a file.
Syntax:
file_object=open(filename,accessmode)
where file_object is used as a handle to the file
file_name-contains a string type value containing the name of the file which
we want to access
access_mode-specifies the mode in which we want to open the file
fp1=open("sample.txt","w")
print(fp1)
fp=open("sample.txt","r")
print(fp)
Output:
<_io.TextIOWrapper name='sample.txt' mode='w' encoding='cp1252'>
<_io.TextIOWrapper name='sample.txt' mode='r'
encoding='cp1252'>
#Example for opening a file when the file does not exists
fp1=open("sample1.txt","r")
print(fp1)
Output:
fp1=open("sample1.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'sample1.txt'
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.
Opens a file for writing only. Overwrites the file if the file
w exists. If the file does not exist, creates a new file for writing.
Opens a file for writing only in binary format. Overwrites the file
wb 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.
Opens a file for appending. The file pointer is at the end of the
a 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.
Opens a file for appending in binary format. The file pointer is at
ab 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.
Opens a file for both appending and reading. The file pointer is at
a+ 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.
Opens a file for both appending and reading in binary format.
ab+ 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.
Note: When opening a file if the access mode is not specified, the file is opened in
read mode
read() method:
The read() enables reading the contents of an opened file.
Syntax:
fileobject.read()
fileobject.read(sie)
where size argument is optional. When the size is not specified, the entire file is read.
When the size is specified, the size number of characters is read. When an empty file
is read, no error is thrown but an empty string is returned.
readline() method:
This method is used for reading a file line by line. This method reads a file till the
newline character including the newline character.
Syntax:
fileobject.readline()
fileobject.readline(size)
where size is optional. When size is specified the size number of characters are
read, otherwise it is similar to read()
readlines() method:
The readlines() method returns a list of lines of the entire file.
Syntax:
fileobject.readlines() fileobject.readlines(size)
When size is not specified, the entire file is read and each line is added as an
element in a list.
Using loop:
A file can be read line by line using for loop
Syntax:
for line in <filevariablename>:
statements for file
operations
Output:
The contents of the file are
This is line1 in file reading
operation The contents of the
file are
This is line2
The contents of the file
are This is line3
The contents of the file
are This is line4
Writing to a file
In order to write into a file, the file has to be opened in “w” mode or “a” mode or
any other writing mode. The “w‟ mode overwrites the file if the file already exists.
If the file does notexist, a new file is opened for writing.
Syntax:
fileobject=open(“filename”,”w”)
write() method:
The write method puts data into the file.
The write() method writes any string to an open file.
The write() method does not add a newline character ('\n') to the end of the string
Syntax:
fileobject.write(string)
Where string is the content that is written to the file
writelines()
The writelines method puts multiple data into the
file. The writelines() method writes any string to
an open file.
Syntax : fileobject.writelines(string)
Output:
Before write operation
After write operation
Example:
#Writing to a file using write()
fp=open("samp.txt","w")
fp.write("This content is written to the file using write()")
fp.close()
Example:
#Writing to a file using writelines()
fp=open("samp1.txt","w")
fp.writelines("This content is written to the file using writelines()\nThis is line2")
fp.close()
Appending a file:
This operation is used to write the content to the end of the file. To perform this
operation, the file has to opened in „a‟ mode
Opening a file in append mode:
Syntax:
fileobject=open(“filename”,”a”)
Example:
#Appending to a file when the file already exists
fp=open("samp1.txt","w")
fp.write("This content is appended to the end of the file")
fp.close()
Before the append operation:
Closing a file:
When the operations that are to be performed on an opened file are finished, the file
has to be closed in order to release the resources. Proper closing of file frees up the
resources held with the file. The closing of file is done with the built-in function
close()
Syntax:
fileobject.close()
Example:
#Closing a file
fp=open("new.txt","r")
print(fp.read()) fp.close()
Output:
This file is closed
The from argument specifies the reference position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end of
the file would be taken as the reference position. If the second argument is omitted, it also
means use the beginning of the file as the reference position.
tell(): The tell() method tells you the current position within the file; in other words, the
next read or write will occur at that many bytes from the beginning of the file.
Syntax:
fileobject.tell()
Example:
“example.txt”
Output:
File is renamed.
Example.py(removing a file)
import os
os.remove('d:/e1.txt')
Output:
File will deleted from the specified path.
FILE METHODS:
S.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.read([size])
Reads at most size bytes from the file (less if the read hits EOF before
obtaining size bytes).
6. file.readline([size])
Reads one entire line from the file. A trailing newline character is kept in
the string.
7. file.readlines([size])
Reads until EOF using readline() and return a list containing the lines. If
the optional size argument is present, instead of reading up to EOF, whole
lines totaling approximately size bytes (possibly after rounding up to an
internal buffer size) are read.
8. file.seek(offset[, whence])
Sets the file's current position
9. file.tell()
Returns the file's current position
10. file.truncate([size])
Truncates the file's size. If the optional size argument is present, the file is
truncated to (atmost) that size.
11. file.write(str)
Writes a string to the file. There is no return value.
12. 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.
13. file.readable()
Returns true if file stream can be read from
14. File.seekable()
Returns true if file stream supports random access.
15. File.writable()
Returns true if file stream can be written to
Example: (for other file methods write examples from file operations)
#File methods
fp=open("samp.txt","w")
print("The file descriptor is",fp.fileno())
print("This is file flush opertion",fp.flush())
print("file is checked for terminal connection",fp.isatty())
print("file truncation",fp.truncate(3))
print("file readable or not",fp.readable())
print("file writable or not",fp.writable())
Output:
The file descriptor is 3
This is file flush opertion None
file is checked for terminal connection
False file truncation 3
file readable or not False file writable or not True
Splitting Words
Python allows you to read line(s) from a file and splits the line (treated as a
string) based on a character. By default, this character is space but you can even specify
any other character to split words in the string.
File Positions
• With every file, the file management system associates a pointer often known as file
pointer that facilitate the movement across the file for reading and/ or writing data. The
file pointer specifies a location from where the current read or write operation is initiated.
Once the read/write operation is completed, the pointer is automatically updated.
• Python has various methods that tells or sets the position of the file pointer. For example,
the tell() method tells the current position within the file at which the next read or write
operation will occur. It is specified as number of bytes from the beginning of the file.
When you just open a file for reading, the file pointer is positioned at location 0, which
is the beginning of the file.
• The seek(offset[, from]) method is used to set the position of the file pointer or in simpler
terms, move the file pointer to a new location. The offset argument indicates the number
of bytes to be moved and the from argument specifies the reference position from where
the bytes are to be moved.
FORMAT OPERATOR:
The argument of write has to be a string, so if we want to put other values in a file,
we have to convert them to strings.
The easiest way to do that is with str()
Example:
>>> f5=open('stringsample.txt','w')
>>> f5.write(5)
TypeError: expected a string or other character buffer object
>>> f5.write(str(5))
An alternative is to use the format operator, %. When applied to integers, % is the
modulus operator. But when the first operand is a string, % is the format operator.
The first operand is the format string, which contains one or more format sequences,
which specify how the second operand is formatted. The result is a string.
For example, the format sequence '%d' means that decimal value is converted to
string.
>>> run=8
>>> '%d'%run
“8‟
The result is the string '8', which is not to be confused with the integer value 8
Format sequences:
Format Conversion
Symbol
%c character
%s string conversion via str() prior to formatting
EXAMPLE:
#Example1
a="python" print("%s"%a)
#Example2
runs=100
matches=3
years=2
print("arun scored %d in runs %d matches in %d years"%(runs,matches,years))
#Example3 print("%s%r"%("hi","bye"))
#Example4
print("%30s" %("I have space before"))
#Example5
print("%-30s"%("I have space after"))
#formatting numbers
#Formatting numbers m=123.4548463749247247828
n="number"
print("%s is %d"%(n,m))
print("%s is %f"%(n,m))
print("Truncate 5 characters %.5s"%m)
print("%s is %10d"%(n,m))
print("%s is %e"%(n,m))
#Format function
print("{1} {0}".format("Python","program"))
Output:
python
arun scored 100 in runs 3 matches in
2 years hi'bye'
I have space
before I have space
after
number is 123
number is 123.454846
Truncate 5 characters 123.4
number is 123
number is
1.234548e+02 program
Python
COMMAND-LINE ARGUMENTS:
It is possible to pass some values from the command line to your python programs when
they are executed. These values are called command line arguments and many times they
are important for your program especially when you want to control your program from
outside instead of hard coding those values inside the code.
The command line arguments are handled using sys module. We can access command- line
arguments via the sys.argv. This serves two purposes −
Example1:
import sys
print("There are %d arguments"%len(sys.argv))
print("Argument are",str(sys.argv))
print("File Name is:",sys.argv[0])
C:\Users\Dhivya>python cmdline.py one two three There are 4 arguments Argument are
['cmdline.py', 'one', 'two', 'three'] File Name is: cmdline.py
The first argument is always script name and it is also being counted in number of
arguments. Here one, two, three are extra inputs passed to program through
command line argument method while running python program command_line.py.
Example2:
import sys
c=sys.argv
i=0
for a in c:
print("Argument",i,"=",a)
i=i+1
Output:
C:\Users\Dhivya>python cmdline1.py one
two three Argument 0 = cmdline1.py
Argument 1 = one Argument 2 = two Argument 3 = three
Example3:
#Program using command line arguments for word count
import sys
if len(sys.argv) != 2:
print('Usage: ./wc.py <filename>')
sys.exit(1)
num_words = num_lines = num_chars = 0
with open(sys.argv[1]) as infile:
for line in infile:
num_lines += 1
num_chars += len(line)
line = line.strip()
words = line.split()
num_words += len(words)
print('Number of Lines is %d' % num_lines)
print('Number of Words is %d' % num_words)
print('Number of Characters is %d' % num_chars)
OUTPUT:
EXCEPTIONS:
An exception is a value (object) that is raised (“thrown”) signaling that an
unexpected, or “exceptional”, situation has occurred. Python contains a predefined
set of exceptions referred to as standard exceptions .
An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions. In general, when a Python
script encounters a situation that it cannot cope with, it raises an exception. An
exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
Errors
1. Syntax error
2. Indentation error
3. Index error
4. Name error
5. Logical error
Example.py (Syntax error)
if x<10
print(X)
Output:
Invalid Syntax
Example.py (Indentation error)
if x<10:
print(X)
Output:
Expected indent block
(line 2)
Example.py (Index error)
a=[1,2,3,4,5]
print(a[10])
Output:
print(a[10])
IndexError: list index out of range
Example.py (Name error)
x=10
print(X)
Output:
print(X)
NameError: name 'X' is not defined
Output:
0
0
0 (infinite loop,since i=i+1 is placed outside while loop)
Python’s built-in exceptions/Standard exceptions
EXCEPTION DESCRIPTION
NAME
Exception Base class for all exceptions
StopIteration Raised when the next() method of an iterator does not
point to any object.
Output:
Traceback (most recent call last):
File "C:/Users/Dhivya/AppData/Local/Programs/Python/Python36-
32/exception.py", line 4, in
<module> c=a/b
ZeroDivisionError: division by zero
Exceptions:(Run Time Error)
Errors detected during execution/runtime are called exceptions.
When that error occurs, Python generate an exception that can be
handled, which avoids your program to crash.
When a Python script raises an exception, it must either handle the
exception immediately otherwise it terminates or quit.
S.N
Exception Name Description
o.
1 FloatingPointError Raised when a floating point calculation fails.
Raised when division or modulo by zero takes place for
2 ZeroDivisionError
all numeric types.
Raised in case of failure of attribute reference or
3 AttributeError
assignment.
4 ImportError Raised when an import statement fails.
Raised when the user interrupts program execution,
5 KeyboardInterrupt
usually by pressing Ctrl+c.
6 IndexError Raised when an index is not found in a sequence
Raised when the specified key is not found in the
7 KeyError
dictionary.
Raised when an identifier is not found in the local or
8 NameError
global namespace
Raised when an input/ output operation fails, such as
9 IOError the print statement or the open() function when trying
to open a file that does not exist.
10 SyntaxError Raised when there is an error in Python syntax.
11 IndentationError Raised when indentation is not specified properly.
Raised when the interpreter finds an internal problem,
12 SystemError but when this error is encountered the Python
interpreter does not exist.
Raised when Python interpreter is quit by using the
13 SystemExit
sys.exit() function. If not handled in the code, causes the
interpreter to exit.
Raised when an operation or function is attempted that
14 TypeError
is invalid for the specified data type.
Raised when the built-in function for a data type has the
15 ValueError valid type of arguments, but the arguments have invalid
values specified.
Raised when a generated error does not fall into any
16 RuntimeError
category.
a.)Built-in exceptions:
Illegal operations can raise exceptions.
There are plenty of built-in exceptions in Python that are raised when
corresponding errors occur.
Exception type Example Description
ZeroDivisionError 10/0 Integer division or modulo by zero
Syntax Error If x<10 Invalid syntax
print(x)
for i in range(4): Invalid syntax
print 'hi'
Indentation Error for i in range(4): Expected an indented block
print(i)
Exception Error X='678'+70 Can't convert 'int' to ‘str’ implicitly
Index Error list1=['22','hi','abc'] list index out of range
print(list1[3])
Name Error X=6 name 'x' is not defined
print(x)
Logical Error score=80 scores is 80, however in program it
if score>50: displays a ‘C’ grade…and not the
print(‘C’) expected ‘B’ grade.
elif score>75:
print(‘B’)
elif score>85:
print(‘A’)
try…except
try… except…else
try…except…else….finally
try…multiple exception
try….except block:
If any code within the try statement causes an error, execution of the
code will stop and jump to the except statement.
The except block will be executed when an exception happens.
The lines after the error line will never be executed in the try block.
Syntax
try:
code that create exception
except:
exception handling statement
Else part will be executed only if the try block doesn’t raise an
exception.
Python will try to process all the statements inside try block. If value error
occurs, the flow of control will immediately pass to the except block and
remaining statement in try block will be skipped.
Syntax
try:
code that create exception
except:
exception handling statement
else:
statements
Example Output
try:
age=int(input("enter your age")) enter your age: six
except: entered value is not a number
print("entered value is not a enter your age:6
number") your age is 6
else:
print("your age is %d:"%(age))
The close( ) method is not entirely safe. If an exception occurs when we are
performing some operation with the file, the code exits without closing
the file.
The finally block is a place to put any code that must execute, whether
the try-block raised an exception or not.
Syntax:
try:
code that create exception
except:
exception handling statement
else:
statements
finally:
statements
Example: Output:
try:
age=int(input("enter your age:")) enter your age: six
except ValueError: entered value is not a number
print("entered value is not a number") Thank you
else: enter your age:5
print("your age :”,age) your age is 5
finally: Thank you
print("Thank you")
try…multiple exception:
Syntax:
try:
code that create exception
except:
exception handling statement
except:
statements
Example Output:
a=int(input("enter a:")) enter a:2
b=int(input("enter b:")) enter b:0
try: cant divide by zero
c=a/b enter a:2
print(c) enter b: h
except ZeroDivisionError: its not a number
print("cant divide by zero")
except ValueError:
print("its not a number")
User-Defined Exceptions:
Python allows users to define their own exceptions by creating a new class. The
exception class is to be derived, directly or indirectly from Exception class.
Example:
#Example for user-defined exception
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
number=10
while True:
try:
n=int(input("Enter a number"))
if(n<number):
raiseValueTooSmallError
elif n>number:
raiseValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small,try again!")
print()
except ValueTooLargeError:
print("This value is too large,try again!")
print()
print("Congratulations! You guessed it correctly")
Output:
Enter a number 5
This value is too small,try again!
Enter a number 10
Congratulations! You guessed it correctly
MODULES
A module is a file consisting of Python code. A module can define functions,
classes and variables. A module can also include runnable code.
Types of modules:
1. Pre-defined modules
2. User-defined modules
Pre-defined modules
These modules are already defined in Python package itself.
Example: math,random,calendar,os,sys,numpy,string etc.,
Example.py
import math print(math.sqrt(16))
print(math.pi)
Output:
4
3.1467
User-defined modules
These modules are created by the user. User has to write function definitions in a file
and give a name with an extension .py Then is name used in python program along
with import keyword. But first this module file has to be executed before the
execution of python program.
Example (calc.py)
Example:(calculator.py) Output
def add(a, b): >>>import calculator
result = a + b >>> mul(2,2)
return (result) 4
def sub(a, b): >>> div(2,2)
result = a - b 1.0
return result >>> add(10,40)
def mul(a, b): 50
result = a * b >>> sub(90,100)
return result -10
def div(a, b): >>> mod(5,10)
result = a / b 5
return result >>> fdiv(30,10)
def mod(a, b): 3
result = a % b
return result
def fdiv(a, b):
result = a // b
return result
Various ways of importing modules
PACKAGES
Packages are namespaces which contain multiple packages and modules themselves.
They are simply directories, but with a change. Each package in Python is a directory
which must contain a special file called init .py. This file can be empty, and it
indicates that the directory it contains is a Python package, so it can be imported the
same way a module can be imported
STEPS TO CREATE A PYTHON PACKAGE
1. Create a directory and give it your package's name.
2. Put your classes in it.
3. Create a init .py file in the directory
The init .py file is necessary because with this file, Python will know that this
directory is a Python package directory other than an ordinary directory (or folder –
whatever you want to call it).
Case Study: Tkinter
GUI
Most of the programs we have seen so far are text-based, but many programs use graphical user interfaces,
also known as GUIs.
Python provides several choices for writing GUI-based programs, including wxPython, Tkinter, and Qt.
To create a GUI, you have to import Gui and instantiate a Gui object:
When you run this code, a window should appear with an empty gray square and the title Gui. mainloop runs
the event loop, which waits for the user to do something and responds accordingly. It is an infinite loop; it
runs until the user closes the window, or presses Control-C, or does something that causes the program to quit.
This Gui doesn’t do much because it doesn’t have any widgets. Widgets are the elements that make up a GUI;
they include:
Button:
A widget, containing text or an image, that performs an action when pressed.
Canvas:
A region that can display lines, rectangles, circles and other shapes.
Entry:
A region where users can type text.
Scrollbar:
A widget that controls the visible part of another widget.
Frame:
A container, often invisible, that contains other widgets.
The empty gray square you see when you create a Gui is a Frame. When you create a new widget, it is added
to this Frame.
The return value from bu is a Button object. The button that appears in the Frame is a graphical representation
of this object; you can control the button by invoking methods on it.
bu takes up to 32 parameters that control the appearance and function of the button. These parameters are
called options. Instead of providing values for all 32 options, you can use keyword arguments,
like text='Press me.', to specify only the options you need and use the default values for the rest.
When you add a widget to the Frame, it gets “shrink-wrapped;” that is, the Frame shrinks to the size of the
Button. If you add more widgets, the Frame grows to accommodate them.
The option that controls the behavior of a button is command. The value of command is a function that gets
executed when the button is pressed. For example, here is a function that creates a new Label:
def make_label():
g.la(text='Thank you.')
When you press this button, it should execute make_label and a new label should appear.
The value of the command option is a function object, which is known as a callback because after you call bu to
create the button, the flow of execution “calls back” when the user presses the button.
This kind of flow is characteristic of event-driven programming. User actions, like button presses and key
strokes, are called events. In event-driven programming, the flow of execution is determined by user actions
rather than by the programmer.
The challenge of event-driven programming is to construct a set of widgets and callbacks that work correctly
(or at least generate appropriate error messages) for any sequence of user actions.
Canvas widgets
One of the most versatile widgets is the Canvas, which creates a region for drawing lines, circles and other
shapes.
After you create a widget, you can still change the values of the options with the config method. For example,
the bg option changes the background color:
canvas.config(bg='white')
The value of bg is a string that names a color. The set of legal color names is different for different
implementations of Python, but all implementations provide at least:
white black
red green blue
cyan yellow magenta
Shapes on a Canvas are called items. For example, the Canvas method circle draws (you guessed it) a circle:
The first argument is a coordinate pair that specifies the center of the circle; the second is the radius.
Gui.py provides a standard Cartesian coordinate system with the origin at the center of the Canvas and the
positive y axis pointing up. This is different from some other graphics systems where the the origin is in the
upper left with the y axis pointing down.
The fill option specifies that the circle should be filled in with red.
The return value from circle is an Item object that provides methods for modifying the item on the canvas.
For example, you can use config to change any of the circle’s options:
Coordinate sequences
The rectangle method takes a sequence of coordinates that specify opposite corners of the rectangle. This
example draws a green rectangle with the lower left corner at the origin and the upper right corner at (200,
100):
This way of specifying corners is called a bounding box because the two points bound the rectangle.
oval takes a bounding box and draws an oval within the specified rectangle:
line takes a sequence of coordinates and draws a line that connects the points. This example draws two legs
of a triangle:
polygon takes the same arguments, but it draws the last leg of the polygon (if necessary) and fills it in:
Tkinter provides two widgets that let users type text: an Entry, which is a single line, and a Text widget, which
has multiple lines.
The text option allows you to put text into the entry when it is created. The get method returns the contents
of the Entry (which may have been changed by the user):
>>> entry.get()
'Default text.'
width and height are the dimensions of the widget in characters and lines.
END is a special index that indicates the last character in the Text widget.
You can also specify a character using a dotted index, like 1.1, which has the line number before the dot and
the column number after. The following example adds the letters 'nother' after the first character of the first
line.
The get method reads the text in the widget; it takes a start and end index as arguments. The following example
returns all the text in the widget, including the newline character:
The delete method removes text from the widget; the following example deletes all but the first two
characters:
Packing widgets
So far we have been stacking widgets in a single column, but in most GUIs the layout is more
complicated. For example, here is a slightly simplified version of TurtleWorld.
At the top level, this GUI contains two widgets—a Canvas and a Frame—arranged in a row. So the first step
is to create the row.
class SimpleTurtleWorld(TurtleWorld):
"""This class is identical to TurtleWorld, but the code that
lays out the GUI is simplified for explanatory purposes."""
def setup(self):
self.row()
...
setup is the function that creates and arranges the widgets. Arranging widgets in a GUI is called packing.
row creates a row Frame and makes it the “current Frame.” Until this Frame is closed or another Frame is
created, all subsequent widgets are packed in a row.
Here is the code that creates the Canvas and the column Frame that hold the other widgets:
The first widget in the column is a grid Frame, which contains four buttons arranged two-by-two:
self.gr(cols=2)
self.bu(text='Print canvas', command=self.canvas.dump)
self.bu(text='Quit', command=self.quit)
self.bu(text='Make Turtle', command=self.make_turtle)
self.bu(text='Clear', command=self.clear)
self.endgr()
gr creates the grid; the argument is the number of columns. Widgets in the grid are layed out left-to-right, top-
to-bottom.
The first button uses self.canvas.dump as a callback; the second uses self.quit. These are bound
methods, which means they are associated with a particular object. When they are invoked, they are invoked
on the object.
The next widget in the column is a row Frame that contains a Button and an Entry:
self.row([0,1], pady=30)
self.bu(text='Run file', command=self.run_file)
self.en_file = self.en(text='snowflake.py', width=5)
self.endrow()
The first argument to row is a list of weights that determines how extra space is allocated between widgets.
The list [0,1] means that all extra space is allocated to the second widget, which is the Entry. If you run this
code and resize the window, you will see that the Entry grows and the Button doesn’t.
The option pady “pads” this row in the y direction, adding 30 pixels of space above and below.
endrow ends this row of widgets, so subsequent widgets are packed in the column Frame. Gui.py keeps a stack
of Frames:
When you use row, col or gr to create a Frame, it goes on top of the stack and becomes the current
Frame.
When you use endrow, endcol or endgr to close a Frame, it gets popped off the stack and the previous
Frame on the stack becomes the current Frame.
The method run_file reads the contents of the Entry, uses it as a filename, reads the contents and passes it
to run_code. self.inter is an Interpreter object that knows how to take a string and execute it as Python
code.
def run_file(self):
filename = self.en_file.get()
fp = open(filename)
source = fp.read()
self.inter.run_code(source, filename)
run_text is similar to run_file except that it takes the code from the Text widget instead of from a file:
def run_text(self):
source = self.te_code.get(1.0, END)
self.inter.run_code(source, '<user-provided code>')
Unfortunately, the details of widget layout are different in other languages, and in different Python modules.
Tkinter alone provides three different mechanisms for arranging widgets. These mechanisms are
called geometry managers. The one I demonstrated in this section is the “grid” geometry manager; the others
are called “pack” and “place”.
Fortunately, most of the concepts in this section apply to other GUI modules and other languages.
A Menubutton is a widget that looks like a button, but when pressed it pops up a menu. After the user selects
an item, the menu disappears.
g = Gui()
g.la('Select a color:')
colors = ['red', 'green', 'blue']
mb = g.mb(text=colors[0])
mb creates the Menubutton. Initially, the text on the button is the name of the default color. The following loop
creates one menu item for each color:
The first argument of mi is the Menubutton these items are associated with.
The command option is a Callable object, which is something new. So far we have seen functions and bound
methods used as callbacks, which works fine if you don’t have to pass any arguments to the function. Otherwise
you have to construct a Callable object that contains a function, like set_color, and its arguments, like color.
The Callable object stores a reference to the function and the arguments as attributes. Later, when the user
clicks on a menu item, the callback calls the function and passes the stored arguments.
def set_color(color):
mb.config(text=color)
print color
When the user selects a menu item and set_color is called, it configures the Menubutton to display the newly-
selected color. It also print the color; if you try this example, you can confirm that set_color is called when
you select an item (and not called when you create the Callable object).
Binding
A binding is an association between a widget, an event and a callback: when an event (like a button press)
happens on a widget, the callback is invoked.
Many widgets have default bindings. For example, when you press a button, the default binding changes the
relief of the button to make it look depressed. When you release the button, the binding restores the appearance
of the button and invokes the callback specified with the command option.
You can use the bind method to override these default bindings or to add new ones.
ca.bind('<ButtonPress-1>', make_circle)
The first argument is an event string; this event is triggered when the user presses the left mouse button. Other
mouse events include ButtonMotion, ButtonRelease and Double-Button.
The second argument is an event handler. An event handler is a function or bound method, like a callback, but
an important difference is that an event handler takes an Event object as a parameter. Here is an example:
def make_circle(event):
pos = ca.canvas_coords([event.x, event.y])
item = ca.circle(pos, 5, fill='red')
The Event object contains information about the type of event and details like the coordinates of the mouse
pointer. In this example the information we need is the location of the mouse click. These values are in “pixel
coordinates,” which are defined by the underlying graphical system. The method canvas_coords translates
them to “Canvas coordinates,” which are compatible with Canvas methods like circle.
For Entry widgets, it is common to bind the <Return> event, which is triggered when the use presses
the Return or Enter key. For example, the following code creates a Button and an Entry.
make_text is called when the Button is pressed or when the user hits Return while typing in the Entry. To
make this work, we need a function that can be called as a command (with no arguments) or as an event handler
(with an Event as an argument):
def make_text(event=None):
text = en.get()
item = ca.text([0,0], text)
make_text gets the contents of the Entry and displays it as a Text item in the Canvas.
It is also possible to create bindings for Canvas items. The following is a class definition for Draggable, which
is a child class of Item that provides bindings that implement drag-and-drop capability.
class Draggable(Item):
The init method takes an Item as a parameter. It copies the attributes of the Item and then creates bindings for
three events: a button press, button motion, and button release.
The event handler select stores the coordinates of the current event and the original color of the item, then
changes the color to yellow:
self.fill = self.cget('fill')
self.config(fill='yellow')
cget stands for “get configuration;” it takes the name of an option as a string and returns the current value of
that option.
drag computes how far the object has moved relative to the starting place, updates the stored coordinates, and
then moves the item.
self.dragx = event.x
self.dragy = event.y
self.move(dx, dy)
This computation is done in pixel coordinates; there is no need to convert to Canvas coordinates.
You can use the Draggable class to add drag-and-drop capability to an existing item. For example, here is a
modified version of make_circle that uses circle to create an Item and Draggable to make it draggable:
def make_circle(event):
pos = ca.canvas_coords([event.x, event.y])
item = ca.circle(pos, 5, fill='red')
item = Draggable(item)
This example demonstrates one of the benefits of inheritance: you can modify the capabilities of a parent class
without modifying its definition. This is particularly useful if you want to change behavior defined in a module
you did not write.
Debugging
One of the challenges of GUI programming is keeping track of which things happen while the GUI is being
built and which things happen later in response to user events.
For example, when you are setting up a callback, it is a common error to call the function rather than passing
a reference to it:
def the_callback():
print 'Called.'
If you run this code, you will see that it calls the_callback immediately, and then creates the button. When
you press the button, it does nothing because the return value from the_callback is None. Usually you do not
want to invoke a callback while you are setting up the GUI; it should only be invoked later in response to a
user event.
Another challenge of GUI programming is that you don’t have control of the flow of execution. Which parts
of the program execute and their order are determined by user actions. That means that you have to design
your program to work correctly for any possible sequence of events.
ILLUSTRATIVE PROGRAMS:
Method 1: COPY FILE USING MODULE
from shutil import copyfile
source=input("enter source file name")
dest=input("enter dest file name")
copyfile("e:/source.txt","e:/dest.txt")
print("File copied successfully")
print("contents of dest file")
fn=open("e:/dest.txt","r")
print(fn.read())
Source.Txt
welcome to
python i am
using module
Output:
enter source file
namee:/source.txt enter dest
file namee:/dest.txt
File copied
successfully
contents of dest file
welcome to python
i am using module
Method 2: COPY FILE WITHOUT USING MODULE
source=input("enter source file name")
dest=input("enter dest file name")
source=open("e:/source.txt","r")
dest=open("e:/dest.txt","w")
for i in source:
dest.write(i)
source.close()
dest.close()
print("File copied successfully")
print("contents of dest file")
fn=open("e:/dest.txt","r")
print(fn.read())
fn.close()
Output:
enter source file nameE:/source.txt
enter dest file namee:/dest.txt
File copied successfully
contents of dest file
welcome to python
i am using module
2.Program for counting words in a file(word count)
Example.py
from collections import Counter
fn=input("enter the file name")
c=open(fn,"r")
print("no. of words in the file")
print(Counter(c.read().split()))
c.close()
Output:
enter the file namee:/source.txt
no. of words in the file
Counter({'welcome': 1, 'to': 1, 'python': 1, 'i': 1, 'am': 1, 'using': 1, 'module': 1})