0% found this document useful (0 votes)
28 views

Unit 6 1

This document discusses input/output operations and file handling in Python. It covers reading keyboard input using raw_input and input functions. It describes opening files in different modes, reading and writing file contents using standard library functions, and closing files. It also discusses renaming, deleting, and creating directories and files using OS module functions. The document then covers exception handling in Python using try, except, else, finally blocks and raising user-defined exceptions by creating custom exception classes.
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)
28 views

Unit 6 1

This document discusses input/output operations and file handling in Python. It covers reading keyboard input using raw_input and input functions. It describes opening files in different modes, reading and writing file contents using standard library functions, and closing files. It also discusses renaming, deleting, and creating directories and files using OS module functions. The document then covers exception handling in Python using try, except, else, finally blocks and raising user-defined exceptions by creating custom exception classes.
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/ 15

6.

1 I/O Operations: Reading keyboard input , Printing to screen

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

The raw_input Function

The raw_input([prompt]) function reads one line from standard input and
returns it as a string.
>>> str = raw_input("Enter your input: ")
Enter your input: mmpolytechnic
>>> print(str)
mmpolytechnic
>>>

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.
>>> str = input("Enter your name: ")
Enter your name: purva
Error:
NameError: name 'purva' is not defined(“for string input” instead of input
use raw_input for accepting string value from user)
>>> str = input("Enter your input: ")
Enter your input: 1
>>> print(str)
1
"6.2 File Handling: Opening file in different modes, accessing file contents
using standard library functions, Reading and writing files, closing a file,
Renaming and deleting file, Directories in python, File and related standard
functions

File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

Opening file in different modes

The key function for working with files in Python is the open() function.

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

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not
exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)


Accessing file contents using standard library functions

Open a File on the Server

Assume we have the following file, located in the same folder as Python:
Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify
how many characters you want to return:
Readline

You can return one line by using the readline() method:

Calling readline() 2 times


By looping through the lines of the file, read the whole file, line by line:

Readlines

Read and return a list of lines from the file. Reads in at most n bytes/
characters if specified.
Reading and writing files

The write() Method


The write() method writes any string to an open file.
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 −

The read() Method


The read() method reads a string from an open 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.
Closing a file

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.

Renaming and deleting file

Python os module provides methods that help you perform file-processing


operations, such as renaming and deleting files.

To use this module you need to import it first and then call any related
functions.

The rename() Method

The rename() method takes two arguments, the current filename and the new
filename.
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.

"6.3 Exception Handling:


An exception can be defined as an abnormal condition in a program resulting
in the disruption in the flow of the program.

Python provides us with the way to handle the Exception so that the other
part of the code can be executed without any disruption. However, if we do
not handle the exception, the interpreter doesn't execute all the code that
exists after that.

Common Exceptions

A list of common exceptions that can be thrown from a normal python


program is given below.

ZeroDivisionError: Occurs when a number is divided by zero.

NameError: It occurs when a name is not found. It may be local or global.

IndentationError: If incorrect indentation is given.

IOError: It occurs when Input Output operation fails.

EOFError: It occurs when the end of the file is reached, and yet operations are
being performed.

Exception Handling- ‘ try: except:’statement

 The try block lets you test a block of code for errors.
 The except block lets you handle the error.
 The finally block lets you execute code, regardless of the result of the
try- and except blocks.

When an error occurs, or exception as we call it, Python will normally stop
and generate an error message.

These exceptions can be handled using the try statement:

Using multiple exceptions:


try:
#block of code

except Exception1:
#block of code

except Exception2:
#block of code

#other code

The use the else statement with the try-except statement, place the code
which will be executed in the scenario if no exception occurs in the try block.
The syntax to use the else statement with the try-except statement is given
below.
If file not present:

If file present:

The finally block


The finally block with the try block in which, we can pace the important code
which must be executed before the try statement throws an exception.

(in given example we open file which is present in directory or filename


where writing code. )
Raise an exception

To throw (or raise) an exception, use the raise keyword.


User defined exceptions.

Python has many built-in exceptions which forces program to output an error
when something in it goes wrong.

However, sometimes need to create a custom exception that serves purpose.

In Python, users can define such exceptions by creating a new class. This
exception class has to be derived, either directly or indirectly, from Exception
class.

You might also like