Unit - 5 Python Notes
Unit - 5 Python Notes
Unit - 5 Python Notes
1.Reading and writing files is a fundamental operation in programming, commonly used for
tasks such as data input/output, configuration management, and logging. brief overview of how
to read from and write to files in Python?
File: File is a named location on disk to store related information. It is used to permanently store data in
a memory (e.g. hard disk).
File Types:
1. Text file
2. Binary file
Python provides built-in functions for creating, writing, and reading files. Two types of files can be
handled in Python, normal text files and binary files (written in binary language, 0s, and 1s).
• Text files: In this type of file, Each line of text is terminated with a special character called
EOL (End of Line), which is the new line character (‘\n’) in Python by default.
• Binary files: In this type of file, there is no terminator for a line, and the data is stored after
converting it into machine-understandable binary language.
File Access Modes
Access modes govern the type of operations possible in the opened file. It refers to how the file
will be used once its opened. These modes also define the location of the File Handle in the file.
The file handle is like a cursor, which defines from where the data has to be read or written in the
file and we can get Python output in text file.
There are 6 access modes in Python:
• Read Only (‘r’)
• Read and Write (‘r+’)
• Write Only (‘w’)
• Write and Read (‘w+’)
• Append Only (‘a’)
• Append and Read (‘a+’)
• Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of
the file. If the file does not exist, raises the I/O error. This is also the default mode in which
a file is opened.
• Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned at
the beginning of the file. Raises I/O error if the file does not exist.
• Write Only (‘w’) : Open the file for writing. For the existing files, the data is truncated
and over-written. The handle is positioned at the beginning of the file. Creates the file if the
file does not exist.
• Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is
truncated and over-written. The handle is positioned at the beginning of the file.
• Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The
handle is positioned at the end of the file. The data being written will be inserted at the end,
after the existing data.
• Append and Read (‘a+’) : Open the file for reading and writing. The file is created if
it does not exist. The handle is positioned at the end of the file. The data being written
will be inserted at the end, after the existing data
Using readline()
Using readlines()
Reading From a File Using read()
read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.
File_object.read([n])
Reading a Text File Using readline()
readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes.
However, does not reads more than one line, even if n exceeds the length of the line.
File_object.readline([n])
readlines() : Reads all the lines and return them as each line a string element in a
list.File_object.readlines()
close() function closes the file and frees the memory space acquired by that file. It is used at the time
when the file is no longer needed or if it is to be opened in a different file mode. File_object.close()
file1 = open("MyFile.txt","a")
file1.close()
import sys
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
# Arguments passed
print("\nName of Python script:", sys.argv[0])
# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int(sys.argv[i])
print("\n\nResult:", Sum)
6. (ii) To implement python program to count a number of lines ,words and characters in a text file ?
SAMPLE.TXT
Hello World
Hello Again
Goodbye
file.close()
OUTPUT
lines: 3 words: 5 characters: 29
7. Mention the commands and their syntax for the following :get current directory,changing directory
list,directories and files make a new directory,renaming and removing directory?
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. The modules that provide the
functionalities are listed below:
• os and os.path
• filecmp
• tempfile
• shutil
os and os.path module
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 and
change it to another. It also allows one to copy files from one directory to another. The major
methods used for directory management is explained below.
# creates in D:\
os.mkdir('D:/new_dir')
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 in case of
both Unix and Windows .
import os
os.rename('file1.txt','file1_renamed.txt')
os.renames('file1.txt', 'D:/file1_renamed.txt')
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.
import os
# Changing directory
os.chdir('/home/nikhil/Desktop/')
print("Current directory :", os.getcwd())
8.(i) illustrative problem to solve to program check whether a person is eligible to vote or
not?
def voter_eligibility(age):
return age >= 18
def main():
try:
age = int(input("Input your age: "))
if age < 0:
print("Age cannot be negative.")
elif voter_eligibility(age):
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
except ValueError:
print("Invalid input. Please input a valid age.")
if __name__ == "__main__":
main()
Output:
8 ii) To write a program for student mark range validation in python using Exception handling ?
def validate_marks(marks):
try:
marks = float(marks)
if marks < 0 or marks > 100:
raise ValueError("Marks should be between 0 and 100")
except ValueError as ve:
print("Error:", ve)
return False
return True
def main():
while True:
marks = input("Enter student marks: ")
if marks.lower() == 'quit':
break
if validate_marks(marks):
print("Valid marks entered.")
if __name__ == "__main__":
main()
5. Create a function that copies a file reading and writing 50 c and character at a time?
# Example usage
src_path = 'source.txt'
dest_path = 'destination.txt'
copy_file(src_path, dest_path)
Exception handling in Python is a process of resolving errors that occur in a program. This involves catching
exceptions, understanding what caused them, and then responding accordingly. Exceptions are errors that occur at
runtime when the program is being executed. They are usually caused by invalid user input or code that is invalid
in Python. Exception handling allows the program to continue to execute even if an error occurs.
try:
# code that may cause an exception
except ExceptionType as e:
# code to handle the exception
else:
# code to execute if no exceptions were raised
finally:
# code that will always be executed, regardless of exceptions
NameError: This Exception is raised when a name is not found in the local or global namespace.
IndexError: This Exception is raised when an invalid index is used to access a sequence.
KeyError: This Exception is thrown when the key is not found in the dictionary.
ValueError: This Exception is thrown when a built-in operation or function receives an argument of the correct
type and incorrect value.
IOError: This Exception is raised when an input/output operation fails, such as when an attempt is made to open a
non-existent file.
ImportError: This Exception is thrown when an import statement cannot find a module definition or a from ...
import statement cannot find a name to import.
SyntaxError: This Exception is raised when the input code does not conform to the Python syntax rules.
TypeError: This Exception is thrown when an operation or function is applied to an object of inappropriate type
AttributeError: occurs when an object does not have an attribute being referenced, such as calling a method that
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)
3. Based on command-line arguments provided by the user, you can modify the script to
accept those arguments and then generate python?
Command line argument: The command line argument is used to pass input from the command line to
your program when they are started to execute.
Handling command line arguments with Python need sys module.
sys module provides information about constants, functions and methods of the pyhton interpretor.
argv[ ] is used to access the command line argument.
The argument list starts from 0. sys.argv[0]= gives file name
sys.argv[1]=provides access to the first input
2. To creating a Python program for managing recipes. The program should
allow users to add new recipes, view existing recipes, and search for recipes by
ingredients. Additionally, users should be able to export the recipe database to
a text file for backup purposes.
Ingredients_have = input("What ingredients do you have?: ")
recipes_dict = {"Hamburger": ["ground beef", "tomato", "onion", "bread"], "Penne alla Vodka": ["pasta",
"vodka", "cream", "canned tomato", "onion", "garlic"], "Pesto Chicken": ["chicken", "pesto", "pasta"]}
available_recipes = []