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

Python Chapter 6 Notes By Ur Engineering Friend

This document covers file input/output handling and exception handling in Python. It explains how to read user input, print output, open files in various modes, and use standard library functions for file manipulation. Additionally, it details exception handling using try and except blocks to manage errors during program execution.

Uploaded by

pranavsp2810
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Python Chapter 6 Notes By Ur Engineering Friend

This document covers file input/output handling and exception handling in Python. It explains how to read user input, print output, open files in various modes, and use standard library functions for file manipulation. Additionally, it details exception handling using try and except blocks to manage errors during program execution.

Uploaded by

pranavsp2810
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Programming with Python

Chapter 6th – File I/O Handling and


Exception Handling

Unit 6 Notes: UR Engineering Friend

I/O Operations: Reading Keyboard Input

In Python, you can read keyboard input from the user using the input() function. This
function reads a line of text from the standard input (keyboard) and returns it as a string.

Here is an example:

name = input("What is your name? ")

print("Hello, " + name + "!")

In this example, we use the input() function to prompt the user to enter their name. The text
"What is your name? " is displayed on the console, and the user can type in their name. Once
they press the Enter key, the input() function reads the line of text and returns it as a string.
We then print a message that includes the user's name.

You can also use the input() function to read numerical input from the user, like this:

age = int(input("What is your age? "))

print("You are " + str(age) + " years old.")

In this example, we read the user's age as a string and then convert it to an integer using the
int() function. We then print a message that includes the user's age as a string.
Note that the input () function always returns a string, so you need to convert it to the
appropriate data type if you want to perform numerical calculations or other operations that
require a different data type.

Printing to Screen

In Python, you can print output to the screen using the print() function. The print() function
takes one or more arguments, and prints them to the standard output (usually the console).

Here are some examples:

print("Hello, world!") # Output: "Hello, world!"

print("The answer is", 42) # Output: "The answer is 42"

➢ In the first example, we use the print() function to print a string "Hello, world!" to the
console.
➢ In the second example, we pass two arguments to the print() function - a string "The
answer is" and an integer 42. The print() function separates the arguments with a
space and prints them to the console.
➢ You can also use formatting to print variables and expressions.

Here is an example:

name = "John"

age = 30

print("My name is {} and I am {} years old.".format(name, age))

In this example, we define two variables name and age, and then use the format() method to
format a string that includes their values. The curly braces {} act as placeholders for the
variables, and the format () method substitutes their values in the string. The resulting output
is "My name is John and I am 30 years old."
File Handling: Opening files in different modes

In Python, you can open files using the open() function. The open() function takes two
arguments: the file name and the mode in which the file should be opened.

Here are the most common modes for opening files in Python:

r - read mode: opens the file for reading (default mode)

w - write mode: opens the file for writing, truncating the file first

x - exclusive creation mode: opens the file for writing, but only if it does not already exist

a - append mode: opens the file for writing, but appends to the end of the file instead of
overwriting it

b - binary mode: opens the file in binary mode instead of text mode

t - text mode: opens the file in text mode (default mode)

To open a file in a specific mode, you can pass the mode as a second argument to the
open() function.

For example:

# Open a file in read mode

file = open("example.txt", "r")

# Open a file in write mode

file = open("example.txt", "w")

# Open a file in append mode

file = open("example.txt", "a")

# Open a binary file in write mode

file = open("example.bin", "wb")


Once you have opened a file, you can read from it or write to it using various methods.

Here are some examples:

# Read the entire contents of a file

content = file.read()

# Read a single line from a file

line = file.readline()

# Write a string to a file

file.write("Hello, world!")

# Append a string to the end of a file

file.write("Hello, again!")

When you are finished using a file, you should close it using the close() method:

file.close()

It is also a good practice to use the with statement when working with files. The with
statement ensures that the file is properly closed after you are done with it, even if an
exception is raised.

Here is an example:

with open("example.txt", "r") as file:

content = file.read()

print(content)
Accessing files using standard library functions

In Python, you can access files using standard library functions such as os, shutil, and glob.
These functions provide a variety of tools for navigating and manipulating files and
directories.

Here are some examples of how to use these functions:

The os module provides functions for interacting with the operating system, including
working with files and directories.

Here are some common functions:

os.path.isfile(path) - checks if a file exists at the specified path

os.path.isdir(path) - checks if a directory exists at the specified path

os.listdir(path) - returns a list of files and directories in the specified path

os.rename(src, dst) - renames a file or directory from src to dst

os.remove(path) - deletes a file at the specified path

os.makedirs(path) - creates a directory at the specified path (and any necessary parent
directories)

Example:

import os

# Check if a file exists

if os.path.isfile("example.txt"):

print("The file exists!")

else:

print("The file does not exist.")


# Get a list of files in a directory

files = os.listdir("my_folder")

print(files)

# Rename a file

os.rename("old_file.txt", "new_file.txt")

# Delete a file

os.remove("old_file.txt")

# Create a directory (and any necessary parent directories)

os.makedirs("my_folder/new_folder")

The shutil module provides functions for working with files and directories. Here are
some common functions:

shutil.copy(src, dst) - copies a file from src to dst

shutil.move(src, dst) - moves a file from src to dst

shutil.rmtree(path) - deletes a directory and all its contents

shutil.make_archive(base_name, format, root_dir) - creates an archive file (e.g., zip or tar) of


the files in root_dir

Example:

import shutil

# Copy a file

shutil.copy("original.txt", "copy.txt")

# Move a file

shutil.move("original.txt", "new_location/original.txt")
# Delete a directory and its contents

shutil.rmtree("my_folder")

# Create a zip archive of a directory

shutil.make_archive("my_archive", "zip", "my_folder")

The glob module provides a way to search for files using wildcard patterns.

Here is an example:

import glob

# Find all files with a .txt extension

txt_files = glob.glob("*.txt")

print(txt_files)

These are just a few examples of the many file access functions available in Python's standard
library. By using these functions, you can easily read, write, move, copy, and delete files and
directories in your Python programs.

Reading and Writing files

In Python, you can read and write files using the built-in open() function. The open() function
returns a file object that you can use to read or write data to the file.

Here is an example of how to read a file:

# Open the file for reading

with open("example.txt", "r") as file:

# Read the contents of the file

contents = file.read()

# Print the contents of the file


print(contents)

In this example, we use the with statement to automatically close the file when we're done
with it. We pass the file name and the mode ("r" for reading) to the open() function, and we
use the read() method of the file object to read the contents of the file.

Here is an example of how to write to a file:

# Open the file for writing

with open("example.txt", "w") as file:

# Write some text to the file

file.write("Hello, world!")

In this example, we pass the file name and the mode ("w" for writing) to the open() function,
and we use the write() method of the file object to write some text to the file.

Here are some other modes you can use with the open() function:

"a" - append mode, which allows you to add data to the end of a file without overwriting its
contents

"x" - exclusive creation mode, which creates a new file but raises an error if the file already
exists

"b" - binary mode, which allows you to read or write binary data (e.g., images or audio files)

Here is an example of how to read a binary file:

# Open a binary file for reading

with open("example.png", "rb") as file:

# Read the contents of the file

contents = file.read()

# Print the length of the file in bytes

print(len(contents))

In this example, we pass the mode "rb" to the open() function to open the file in binary mode,
and we use the read() method of the file object to read the contents of the file.
In addition to the read() and write() methods, file objects also have other useful methods,
such as readline() and writelines(). You can find more information about file objects in the
Python documentation.

Closing a File

In Python, it is important to close a file after you have finished reading from it or writing to
it. This ensures that all data is properly written to the file and that resources are freed up in
your system.

To close a file in Python, you can use the close() method of the file object.

Here is an example of how to close a file after reading from it:

# Open the file for reading

file = open("example.txt", "r")

# Read the contents of the file

contents = file.read()

# Close the file

file.close()

➢ In this example, we first open the file for reading using the open() function and assign
the resulting file object to the variable file. We then read the contents of the file using
the read() method of the file object, and finally close the file using the close() method
of the file object.
➢ It is important to note that when you use the with statement, the file is automatically
closed for you when the block of code inside the with statement is exited.

Here is an example of how to use the with statement to read from a file and
automatically close it:
# Open the file for reading using the with statement

with open("example.txt", "r") as file:

# Read the contents of the file

contents = file.read()

# The file is automatically closed when the block inside the with statement is exited

In this example, we use the with statement to open the file for reading and assign the resulting
file object to the variable file. We then read the contents of the file inside the with block, and
the file is automatically closed for us when we exit the block.

Renaming and Deleting files

In Python, you can rename and delete files using the built-in os module.

To rename a file, you can use the os.rename() method. Here is an example of how to
rename a file:

import os

# Rename a file

os.rename("old_file.txt", "new_file.txt")

In this example, we use the os.rename() method to rename a file called "old_file.txt" to
"new_file.txt". The os.rename() method takes two arguments: the current name of the file,
and the new name of the file.

To delete a file, you can use the os.remove() method. Here is an example of how to delete
a file:

import os

# Delete a file

os.remove("file_to_delete.txt")
➢ In this example, we use the os.remove() method to delete a file called
"file_to_delete.txt". The os.remove() method takes one argument: the name of the file
to delete.
➢ It's important to note that both the os.rename() and os.remove() methods can raise
errors if the specified file does not exist, or if you don't have permission to rename or
delete the file. You can catch these errors using a try-except block.

Directories in Python

➢ In Python, you can work with directories (also known as folders) using the built-in os
module.
➢ To create a new directory, you can use the os.mkdir() method.

Here is an example of how to create a new directory:

import os

# Create a new directory

os.mkdir("new_directory")

In this example, we use the os.mkdir() method to create a new directory called
"new_directory". The os.mkdir() method takes one argument: the name of the directory to
create.

To check if a directory exists, you can use the os.path.exists() method.

Here is an example of how to check if a directory exists:

import os

# Check if a directory exists

if os.path.exists("existing_directory"):

print("The directory exists.")

else:
print("The directory does not exist.")

In this example, we use the os.path.exists() method to check if a directory called


"existing_directory" exists. The os.path.exists() method returns True if the specified path
exists, and False otherwise.

To delete a directory, you can use the os.rmdir() method. Here is an example of how to
delete a directory:

import os

# Delete a directory

os.rmdir("directory_to_delete")

➢ In this example, we use the os.rmdir() method to delete a directory called


"directory_to_delete". The os.rmdir() method takes one argument: the name of the
directory to delete.
➢ It's important to note that the os.rmdir() method can only delete empty directories. If
the directory contains any files or subdirectories, you will need to delete them first
before you can delete the directory using os.rmdir().

File and Directory related standard functions

In Python, you can work with files and directories using the built-in os and os.path modules.
Here are some commonly used functions and methods:

Functions for working with directories:

1. os.mkdir(path): creates a new directory with the specified path.


2. os.rmdir(path): removes an empty directory with the specified path.
3. os.listdir(path): returns a list of all files and directories in the specified directory.
Exception Handling

➢ The cause of an exception is often external to the program itself. For example, an
incorrect input, a malfunctioning IO device etc. Because the program abruptly
terminates on encountering an exception, it may cause damage to system resources,
such as files. Hence, the exceptions should be properly handled so that an abrupt
termination of the program is prevented.
➢ Python uses try and except keywords to handle exceptions. Both keywords are
followed by indented blocks.

Syntax:
try :
#statements in try block
except :
#executed when error in try block

➢ The try: block contains one or more statements which are likely to encounter an
exception. If the statements in this block are executed without an exception, the
subsequent except: block is skipped.
➢ If the exception does occur, the program flow is transferred to the except: block.
The statements in the except: block are meant to handle the cause of the exception
appropriately. For example, returning an appropriate error message.
➢ You can specify the type of exception after the except keyword. The subsequent
block will be executed only if the specified exception occurs. There may be
multiple except clauses with different exception types in a single try block. If the
type of exception doesn't match any of the except blocks, it will remain unhandled
and the program will terminate.
➢ The rest of the statements after the except block will continue to be executed,
regardless if the exception is encountered or not.
The following example will throw an exception when we try to devide an integer by a
string.

Example: try...except blocks


Copy
try:
a=5
b='0'
print(a/b)
except:
print('Some error occurred.')
print("Out of try except blocks.")

Output
Some error occurred.
Out of try except blocks.

You can mention a specific type of exception in front of the except keyword. The
subsequent block will be executed only if the specified exception occurs. There may be
multiple except clauses with different exception types in a single try block. If the typ e of
exception does not match any of the except blocks, it will remain unhandled and the
program will terminate.

Example: Catch Specific Error Type


try:
a=5
b='0'
print (a+b)
except TypeError:
print('Unsupported operation')
print ("Out of try except blocks")
Output
Unsupported operation
Out of try except blocks

As mentioned above, a single try block may have multiple except blocks. The following
example uses two except blocks to process two different exception types:

Example: Multiple except Blocks


try:
a=5
b=0
print (a/b)
except TypeError:
print('Unsupported operation')
except ZeroDivisionError:
print ('Division by zero not allowed')
print ('Out of try except blocks')

Output
Division by zero not allowed
Out of try except blocks

However, if variable b is set to '0', Type Error will be encountered and processed by
corresponding except block.

You might also like