0% found this document useful (0 votes)
7 views25 pages

Python File Handling & Exception

The document provides an overview of file handling and exception handling in Python, detailing how to open, read, write, rename, and delete files using built-in functions and the os module. It also explains exception handling, including try-except blocks, built-in and user-defined exceptions, and how to manage errors effectively. Key methods and their syntax are presented to guide users in manipulating files and handling exceptions in their Python programs.

Uploaded by

detonmoy800
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)
7 views25 pages

Python File Handling & Exception

The document provides an overview of file handling and exception handling in Python, detailing how to open, read, write, rename, and delete files using built-in functions and the os module. It also explains exception handling, including try-except blocks, built-in and user-defined exceptions, and how to manage errors effectively. Key methods and their syntax are presented to guide users in manipulating files and handling exceptions in their Python programs.

Uploaded by

detonmoy800
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

File Handling and Exception

Handling in Python
 Files
 Python provides basic functions and methods necessary to manipulate files by default. You can
do most of the file manipulation using a file object.
 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 are parameter details-
  file_name: The file_name argument is a string value that contains the name of the file that
you want to access.
  access_mode: The access_mode determines the mode in which the file has to be opened,
i.e., read, write, append, etc.
 A complete list of possible values is given below in the table. This is an optional parameter and
the default file access mode is read (r).
  buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is
1, line buffering is performed while accessing a file. If you specify the buffering value as an
integer greater than 1, then buffering action is performed with the indicated buffer size. If
negative, the buffer size is the system default (default behavior).
 The File Object Attributes :
 Once a file is opened and you have one file object, you can get various information related to
that file.
 Here is a list of all the attributes related to a file object-

Note: softspace attribute is not supported in Python 3.x


 The close() Method
 The close() method of a file object flushes any unwritten information and closes the file object,
after which no more writing can be done.
 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
 [Link]();
 Example
 #!/usr/bin/python3
 # Open a file
 fo = open("[Link]", "wb")
 print ("Name of the file: ", [Link])
 # Close opened file [Link]()
 This produces the following result-
 Name of the file: [Link]
 Reading and Writing Files
 The file object provides a set of access methods to make our lives easier. We would see how to
use read() and write() methods to read and write files.
 ------------------------------------------------------------------------------------------------------------
 The write() Method
 The 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.
 The write() method does not add a newline character ('\n') to the end of the string-
 Syntax
 [Link](string);
 Here, passed parameter is the content to be written into the opened file.
 # Open a file
 fo = open("[Link]", "w")
 [Link]( "Python is a great language.\nYeah its great!!\n")
 # Close opend file [Link]()
 The above method would create [Link] 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 the following content-
 The read() Method
 The read() method reads a string from an open file. It is important to note that Python strings
can have binary data apart from the text data.
 Syntax
 [Link]([count]);
 Here, passed parameter is the number of bytes to be read from the opened file. This method
starts reading from the beginning of the file and if count is missing, then it tries to read as much
as possible, maybe until the end of file.
 Example
 Let us take a file [Link], w
 # Open a file
 fo = open("[Link]", "r+") str = [Link](10)
 print ("Read String is : ", str)
 # Close opened file [Link]() which we created above.
 File Positions :

 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.

 The seek(offset[, from]) method changes the current file position. The offset
argument indicates the number of bytes to be moved. The from argument specifies
the reference position from where the bytes are to be moved.

 If from is set to 0, the beginning of the file is used as the reference position. If it is set
to 1, the current position is used as the reference position. If it is set to 2 then the
end of the file would b
 # Open a file
 fo = open("[Link]", "r+") str = [Link](10)
 print ("Read String is : ", str)
 # Check current positione taken as the reference position.
 position = [Link]()
 print ("Current file position : ", position)
 # Reposition pointer at the beginning once again position = [Link](0, 0)
 str = [Link](10)
 print ("Again read String is : ", str)
 # Close opened file [Link]()

 This produces the following result-


 Read String is : Python is Current file position : 10
 Again read String is : Python is
 Renaming and Deleting Files
 Python os module provides methods that help you perform file-processing operations, such as
renaming and deleting files.

 The rename()Method
 The rename() method takes two arguments, the current filename and the new filename.
 Syntax
 [Link](current_file_name, new_file_name)
 Example
 Following is an example to rename an existing file [Link]-
 #!/usr/bin/python3 import os
 # Rename a file from [Link] to [Link] [Link]( "[Link]", "[Link]" )
 The remove() Method
 You can use the remove() method to delete files by supplying the name of the file to be
deleted as the argument.
 Syntax
 [Link](file_name)
 Example
 Following is an example to delete an existing file [Link]-
 #!/usr/bin/python3 import os
 # Delete file [Link] [Link]("[Link]")
 Directories :
 All files are contained within various directories, and Python has no problem handling these
too.
 The os module has several methods that help you create, remove, and change directories.

 The mkdir() Method


 You can use the mkdir() method of the os module to create directories in the current directory.
You need to supply an argument to this method, which contains the name of the directory to
be created.
 Syntax
 [Link]("newdir")

 #!/usr/bin/python3 import os
 # Create a directory "test" [Link]("test")
 The chdir() Method
 You can use the chdir() method to change the current directory.
 The chdir() method takes an argument, which is the name of the directory that you want to
make the current directory.

 Syntax
 [Link]("newdir")
 Example
 Following is an example to go into "/home/newdir" directory-
 #!/usr/bin/python3 import os
 # Changing a directory to "/home/newdir" [Link]("/home/newdir")
 The getcwd() Method
 The getcwd() method displays the current working directory.
 Syntax :
 [Link]()
 #!/usr/bin/python3 import os
 # This would give location of the current directory [Link]()
 ---------------------------------------------------------------------------------------------------------
 The rmdir() Method
 The rmdir() method deletes the directory, which is passed as an argument in the method.
Before removing a directory, all the contents in it should beremoved.
 Syntax :
 [Link]('dirname')
 import os
 # This would remove "/tmp/test" directory.
 [Link]( "/tmp/test" )
 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.
 Python provides two types of exceptions i.e. 1)built-in 2)user defined
 Built-in Exceptions
 :
 Handling Exceptions :
 If you have some suspicious code that may raise an exception, you can defend your program
by placing the suspicious code in a try: block. After the try: block, include an except:
statement, followed by a block of code which handles the problem as elegantly as possible.
 Syntax
 Here is simple syntax of
 try....except...else blocks-
 Here are few important points about the above-mentioned syntax-
 • A single try statement can have multiple except statements. This is useful when the try block
contains statements that may throw different types of exceptions.

 • You can also provide a generic except clause, which handles any exception.

 • After the except clause(s), you can include an else-clause. The code in the else- block
executes if the code in the try: block does not raise an exception.

 • The else-block is a good place for code that does not need the try: block's protection.
 Example:
 #!/usr/bin/python3
 try:
 fh = open("testfile", "w")
 [Link]("This is my test file for exception handling!!")
 except IOError:
 print ("Error: can\'t find file or read data")
 else:
 print ("Written content in the file successfully") [Link]()
 Exception with Arguments :
 An exception can have an argument, which is a value that gives additional
information about the problem. The contents of the argument vary by exception. You
capture an exception's argument by supplying a variable in the except clause as
follows-

If you write the code to handle a single exception, you can have a variable follow the name of the
exception in the except statement. If you are trapping multiple exceptions, you can have a
variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the exception. The
variable can receive a single value or multiple values in the form of a tuple. This tuple usually
contains the error string, the error number, and an error location.
 Example
 Following is an example for a single exception-
 #!/usr/bin/python3
 # Define a function here.
 def temp_convert(var):
 try:
 return int(var)
 except ValueError as Argument:
 print("The argument does not contain numbers\n",Argument)
 # Call above function here.
 temp_convert("xyz")
 o/p

 The argument does not contain numbers invalid literal for int() with base 10: 'xyz'
 User-defined Exceptions :
 Python also allows you to create your own exceptions by deriving classes from the standard
built-in exceptions.
 Here is an example related to RuntimeError. Here, a class is created that is subclassed from
RuntimeError. This is useful when you need to display more specific information when an
exception is caught.
 In the try block, the user-defined exception is raised and caught in the except block. The
variable e is used to create an instance of the class Networkerror.
 class Networkerror(RuntimeError):
 def __init__ (self, arg):
 [Link] = arg
 So, once you have defined the above class, you can raise the exception as follows-
 try:
 raise Networkerror("Bad hostname")
 except Networkerror as e:
 print([Link])
 o/p
 Bad hostname

You might also like