Python Chapter 6 Notes By Ur Engineering Friend
Python Chapter 6 Notes By Ur Engineering Friend
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:
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:
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).
➢ 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
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:
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
To open a file in a specific mode, you can pass the mode as a second argument to the
open() function.
For example:
content = file.read()
line = file.readline()
file.write("Hello, world!")
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:
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.
The os module provides functions for interacting with the operating system, including
working with files and directories.
os.makedirs(path) - creates a directory at the specified path (and any necessary parent
directories)
Example:
import os
if os.path.isfile("example.txt"):
else:
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")
os.makedirs("my_folder/new_folder")
The shutil module provides functions for working with files and directories. Here are
some common functions:
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")
The glob module provides a way to search for files using wildcard patterns.
Here is an example:
import glob
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.
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.
contents = file.read()
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.
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)
contents = file.read()
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.
contents = file.read()
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
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.
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.
import os
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.
import os
if os.path.exists("existing_directory"):
else:
print("The directory does not exist.")
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 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:
➢ 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.
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.
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:
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.