0% found this document useful (0 votes)
33 views118 pages

Chapter-Vi File Handling & Exception Handling

PYTHON PPT for Chapter 6 msbte
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views118 pages

Chapter-Vi File Handling & Exception Handling

PYTHON PPT for Chapter 6 msbte
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 118

PROGRAMMING WITH PYTHON

PWP - 22616

UNIT-VI
FILE HANDLING & EXCEPTION HANDLING

Mr. Naresh A. Kamble


POINTS TO BE COVERED
• INTRODUCTION TO FILES
• I/O OPERATIONS
• FILE HANDLING
• EXCEPTION HANDLING

2
3
POINTS TO BE COVERED
• INTRODUCTION
• READING KEYBOARD INPUT
• PRINTING ON SCREEN

4
5
INTRODUCTION
What is a file?
• It is a kind of permanent storage consuming less memory but
satisfies the user basic needs.

• A file can be of any type


– Audio

– Video

– Text

– Image

6
7
I/O OPERATIONS ON FILE
• The key function for working with files in Python is the open()
function.

• The open() function takes two parameters; filename, and


mode.

open (filename, mode)

8
I/O OPERATIONS ON FILE
• There are four different methods (modes) for opening a file:

9
I/O OPERATIONS ON FILE
open (filename, r)

open (filename, w)

open (filename, a)

open (filename, x)

10
I/O OPERATIONS ON FILE
• In addition you can specify if the file should be handled as
binary or text mode

11
I/O OPERATIONS ON FILE

open (filename, t)

open (filename, b)

12
I/O OPERATIONS ON FILE
• Hence, in Python, a file operation takes place in the following
order:

• Open a file

• Read or write (perform operation)

• Close the file

13
14
I/O OPERATIONS ON FILE
• WORKING OF OPEN() FUNCTION

• Before performing any operation on the file like read or write,


first we have to open that file.

• For this, we should use Python’s inbuilt function open()

• But at the time of opening, we have to specify the mode,


which represents the purpose of the opening file.

15
I/O OPERATIONS ON FILE

16
I/O OPERATIONS ON FILE

17
18
I/O OPERATIONS ON FILE
• WORKING OF READ() MODE

• There is more than one way to read a file in Python.

• If you need to extract a string that contains all characters in


the file then we can use file.read()

19
I/O OPERATIONS ON FILE

20
I/O OPERATIONS ON FILE
• WORKING OF READ() MODE

• Another way to read a file is to call a certain number of


characters.

• The interpreter will read the certain number of characters of


stored data and return it as a string.

21
I/O OPERATIONS ON FILE

22
23
I/O OPERATIONS ON FILE
• WORKING OF WRITE() MODE
• It is used for manipulating contents in a file.

• If the file that we are trying to open is not present in pwd,


then a new file is created.

• The write() mode over writes the contents in a file.

• It does not preserve integrity of a file.


24
I/O OPERATIONS ON FILE

25
I/O OPERATIONS ON FILE

26
27
I/O OPERATIONS ON FILE
• WORKING OF APPEND() MODE

• It is used for manipulating contents in a file.

• It does not over writes the new content over the old contents
like write() mode.

• Executing append() mode for multiple time, appends same


statement for n number of times.

28
I/O OPERATIONS ON FILE

29
I/O OPERATIONS ON FILE

30
31
I/O OPERATIONS ON FILE
• WORKING OF X() MODE

• It is creating a file.

• If the file that we are trying to open is not present in pwd,


then a new file is created.

• But if the file exist, then an error message is shown.

32
I/O OPERATIONS ON FILE

BEFORE EXECUTION

AFTER EXECUTION

33
34
I/O OPERATIONS ON FILE
• WORKING OF T() & B() MODE

• The t() mode is default mode for text.

• The b() mode is used for images.

• The b() mode reads and writes in binary mode

35
I/O OPERATIONS ON FILE

36
37
I/O OPERATIONS ON FILE
• ATTRIBUTES OF FILE

• Once a file is opened, we have one file object. To get various


information related to that file using following attributes.

• 1. file.closed – Returns True if file is closed, false otherwise.

• 2. file.mode – Returns access mode with which file was


opened.

• 3. file.name – Returns name of the file.

• 4. file.softspace – Returns 0 is space is explicitly required with


print, or 1 otherwise.
38
I/O OPERATIONS ON FILE

39
I/O OPERATIONS ON FILE

40
41
I/O OPERATIONS ON FILE

42
I/O OPERATIONS ON FILE
• TRY IT YOURSELF

• Consider you have created a file named ‘demo.txt’. Write a python


program to take input as name of file from user.

• If the user types the file name correct (‘demo.txt’), then print “File
Exist” and read the file contents and print each line one by one.

• If the user types the file name incorrect, then print “File does not
exist” and print “End of Program”

43
I/O OPERATIONS ON FILE

44
I/O OPERATIONS ON FILE

45
46
I/O OPERATIONS ON FILE
• FILE METHODS

• file.no()

• file.seek()

• file.tell()

• file.truncate()

• file.readlines()

47
I/O OPERATIONS ON FILE

48
49
50
51
52
53
54
55
I/O OPERATIONS ON FILE
• RENAMING A FILE
• To rename a file, we must use os module.

• It provides methods to perform file operations.

• To rename an existing file, we can use rename() method.

• This method takes two arguments , current filename and new


file name.
56
I/O OPERATIONS ON FILE

os.rename (current_filename, new_filename)

57
BEFORE EXECUTION AFTER EXECUTION

58
I/O OPERATIONS ON FILE
• DELETING A FILE

• To deleting a file, we must use os module.

• It provides methods to perform file operations.

• To delete an existing file, we can use remove() method.

• This method takes one argument , filename


59
I/O OPERATIONS ON FILE

os.remove(filename)

60
BEFORE EXECUTION AFTER EXECUTION

61
62
DIRECTORIES

WHAT IS A DIRECTORY?
• A directory or folder is a collection of files and subdirectories.

• Python has the os module that provides us with many useful


methods to work with directories (and files as well).

63
DIRECTORIES
WHAT IS A DIRECTORY?
• Directories are a way of storing, organizing, and separating
the files on a computer.
• The directory that does not have a parent is called a root
directory.
• The way to reach the file is called the path.
• The path contains a combination of directory names, folder
names separated by slashes and colon and this gives the route
to a file in the system.
64
65
DIRECTORIES
• DIRECTORY MANAGEMENT

• Python contains several modules that has a number of built-in


functions to manipulate and process data.

• Python has also provided modules that help us to interact


with the operating system and the files.

• These kinds of modules can be used for directory


management also.
66
DIRECTORIES
• DIRECTORY MANAGEMENT

• The modules that provide the functionalities are listed below:

• os and os.path

• filecmp

• tempfile

• shutil

67
68
DIRECTORIES
• 1. OS AND OS.PATH MODULES
• The os module is used to handle files and directories in various
ways.

• It provides provisions to create/rename/delete directories.

• This allows even to know the current working directory (CWD) and
change it to another.

• It also allows one to copy files from one directory to another.


69
DIRECTORIES
• There are different methods for directory management
– Creating New Directory

– Getting Current Working Directory (CWD)

– Changing Current Working Directory (CWD)

– Renaming a Directory

– Listing files in a Directory

– Removing a Directory

– Checking Directory (It is / It is not)

– Size of Directory

– Getting access and modification times

70
DIRECTORIES
• OS AND OS.PATH MODULES

• A. CREATING NEW DIRECTORY:

• os.mkdir (name) method to create a new directory.

• The desired name for the new directory is passed as the parameter.

• By default it creates the new directory in the current working


directory.

• If the new directory has to be created somewhere else then that


path has to be specified and the path should contain forward
slashes instead of backward ones.

71
DIRECTORIES

os.mkdir(Drive name/directoryname)

72
73
BEFORE EXECUTION

74
AFTER EXECUTION

75
DIRECTORIES
• OS AND OS.PATH MODULES

• B. GETTING CURRENT WORKING DIRECTORY (CWD):

• os.getcwd() can be used.

• It returns a string that represents the path of the current


working directory.

• os.getcwdb() can also be used but it returns a byte string that


represents the current working directory.

• Both methods do not require any parameters to be passed.

76
77
DIRECTORIES
• OS AND OS.PATH MODULES

• C. CHANGING CURRENT WORKING DIRECTORY (CWD):

• Every process in the computer system will have a directory


associated with it, which is known as Current Working
Directory(CWD).

• os.chdir() method is used to change it.

• The parameter passed is the path/name of the desired


directory to which one wish to shift.

78
DIRECTORIES

os.chdir(path/name)

79
80
DIRECTORIES
• OS AND OS.PATH MODULES

• D. RENAMING A DIRECTORY:

• os.rename() method is used to rename the directory.

• The parameters passed are old_name followed by new_name.

• If a directory already exists with the new_name passed,


OSError will be raised.

• os.renames(‘old_name’,’dest_dir:/new_name’) method
works similar to os.rename() but it moves the renamed file to
the specified destination directory(dest_dir).
81
DIRECTORIES

os.rename(old_name,new_name)

82
BEFORE EXECUTION AFTER EXECUTION

83
DIRECTORIES
• OS AND OS.PATH MODULES

• E. LISTING THE FILES IN A DIRECTORY:

• A directory may contain sub-directories and a number of files in it.


To list them, os.listdir() method is used.

• It either takes no parameter or one parameter.

• If no parameter is passed, then the files and sub-directories of the


CWD is listed.

• If files of any other directory other than the CWD is required to be


listed, then that directory’s name/path is passed as parameter.

84
DIRECTORIES

os.listdir()

os.listdir(os.getcwd())

85
86
DIRECTORIES
• OS AND OS.PATH MODULES

• F. REMOVING A DIRECTORY:

• os.rmdir() method is used to remove/delete a directory.

• The parameter passed is the path to that directory.

• It deletes the directory if and only if it is empty, otherwise


raises an OSError.

87
88
DIRECTORIES
• OS AND OS.PATH MODULES

• G. TO CHECK WHETHER IT IS A DIRECTORY:

• Given a directory name or Path, os.path.isdir(path) is used to


validate whether the path is a valid directory or not.

• It returns Boolean values only.

• Returns true if the given path is a valid directory otherwise


false.

89
90
91
DIRECTORIES
• OS AND OS.PATH MODULES

• G. TO GET SIZE OF THE DIRECTORY:

• os.path.getsize(path_name) gives the size of the directory in


bytes.

• OSError is raised if, invalid path is passed as parameter.

92
DIRECTORIES

os.path.getsize(path_name)

93
94
DIRECTORIES
• OS AND OS.PATH MODULES

• G. GETTING ACCESS AND MODIFICATION TIMES:

• To get the last accessed time of a directory : os.path.getatime


(path)

• To get the last modified time of the directory :


os.path.getmtime (path)

• These methods return the number of seconds since the


epoch. To format it, datetime module’s strftime( ) function
can be used.
95
DIRECTORIES

os.path.getatime (path)

os.path.getmtime (path)

96
97
DIRECTORIES
• 2. FILECMP MODULE

• This module provides various functions to perform


comparison between files and directories.

• To compare the directories, an object has to be created for


the class filecmp.dircmp that describes which files to ignore
and which files to hide from the functions of this class.

• The constructor has to be invoked before calling any of the


functions of this class.

98
DIRECTORIES
• 3. TEMPFILE MODULE

• This module is used to create temporary files and directories.

• This creates the temporary files and directories in the temp


directories created by the Operating systems.

99
DIRECTORIES
• 3. SHUTIL MODULE

• This module is concerned with number of high-level


operations on files and directories.

• It allows copying/moving directories from a source to


destination.

100
101
EXCEPTION HANDLING
• INTRODUCTION

• Error in Python can be of two types i.e. Syntax errors and


Exceptions.

• Errors are the problems in a program due to which the


program will stop the execution.

• On the other hand, exceptions are raised when some internal


events occur which changes the normal flow of the program.
102
EXCEPTION HANDLING
• DIFFERENCE BETWEEN SYNTAX ERROR AND EXCEPTIONS

• Syntax Error: As the name suggests this error is caused by the


wrong syntax in the code. It leads to the termination of the
program.

• Exceptions: Exceptions are raised when the program is


syntactically correct, but the code resulted in an error. This
error does not stop the execution of the program, however, it
changes the normal flow of the program.
103
104
105
106
EXCEPTION HANDLING
• TRY AND EXCEPT STATEMENT – CATCHING EXCEPTIONS

• Try and except statements are used to catch and handle


exceptions in Python.

• Statements that can raise exceptions are kept inside the try
clause and the statements that handle the exception are
written inside except clause.

107
108
EXCEPTION HANDLING
• CATCHING SPECIFIC EXCEPTION

• A try statement can have more than one except clause, to


specify handlers for different exceptions.

• The general syntax for adding specific exceptions are –

109
110
111
112
EXCEPTION HANDLING
• RAISE STATEMENT

• The raise statement allows the programmer to force a specific


exception to occur.

• The sole argument in raise indicates the exception to be


raised.

• This must be either an exception instance or an exception


class (a class that derives from Exception).
113
114
115
EXCEPTION HANDLING
• CREATING USER-DEFINED EXCEPTION

• Programmers may name their own exceptions by creating a new


exception class.

• Exceptions need to be derived from the Exception class, either


directly or indirectly.

• Although not mandatory, most of the exceptions are named as


names that end in “Error” similar to the naming of the standard
exceptions in python. 116
117
118

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy