Unit 06. PWP (22616)
Unit 06. PWP (22616)
Q3. With neat example differentiate between readline () and readlines ( ) functions in file-
handling.
Ans:-
1) readline( ) Function
Each time it is called, it reads the next line from the file.
Example:
file = open("example.txt", "r") # Open file in read mode
print(file.readline()) # Reads the first line
print(file.readline()) # Reads the second line
file.close()
Output:
Hello, welcome to Python!
This is a file handling tutorial.
(Only two lines are read)
2) readlines( ) Function
Useful when you need to store all lines in memory for processing.
Example:
file = open("example.txt", "r") # Open file in read mode
lines = file.readlines() # Reads all lines and stores them in a list
print(lines) # Prints the list of lines
file.close()
Output:
['Hello, welcome to Python!\n', 'This is a file handling tutorial.\n', 'Have a great
day!\n']
Key Differences
Reads how many lines? One line at a time All lines at once
Best for reading large files Best when you need all
Usage
line by line lines at once
Marathi (टीप)
readline( ) – एका वेळी फक्त एक ओळ वाचते. मोठ्या फायलीींसाठी चाींगले आहे .
readlines( ) – सवव ओळी यादी (list) स्वरूपात वाचते. लहान फायलीींसाठी चाींगले आहे .
Q4. State the use of read() and readline () functions in python file handling.
Ans:- 1) read([n]) Method
Functionality:
Reads entire file content and returns it as a string.
If a number n is specified, it reads only first n bytes/characters.
If n is not given, it reads the whole file.
Example:
f = open("sample.txt", "r") # Open file in read mode
print(f.read(5)) # Read first 5 characters
print(f.read()) # Read the rest of the file
f.close() # Close the file
Output:
Pytho
n is fun!
Let's learn file handling.
(First 5 characters read separately, then the rest of the file is read.)
2) readline([n]) Method
Functionality:
Reads one line at a time from the file.
If n is specified, it reads only first n bytes/characters from the line.
If EOF (End of File) is reached, it returns an empty string.
Example:
f = open("sample.txt", "r") # Open file in read mode
print(f.readline()) # Read the first line
print(f.readline(3)) # Read first 3 characters of the second line
print(f.readline()) # Read the remaining part of the second line
f.close() # Close the file
Output:
Python is fun!
Let
's learn file handling.
(First line is fully read, then only first 3 characters of the second line, and finally, the rest of the
second line.)
Q5. Explain seek ( ) and tell ( ) function for file pointer manipulation in python with example.
Ans:-
1) seek() Function
Functionality:
Used to move the file pointer (cursor) to a specific position in the file.
Controls where the next read or write operation will start.
Syntax:
f.seek(offset, from_where)
• offset: Number of bytes/characters to move.
• from_where: The reference position (default = 0).
o 0 → Beginning of the file
o 1 → Current position (only in binary mode)
o 2 → End of the file (only in binary mode)
Example:
f = open("demofile.txt", "r") # Open file in read mode
f.seek(4) # Move cursor to the 4th character from the start
print(f.readline()) # Read from the new position
f.close()
Example File (demofile.txt):
Hello, Python!
Welcome to file handling.
Output:
o, Python!
(The first 4 characters 'Hell' are skipped, and reading starts from the 5th character.)
2) tell() Function
Functionality:
Returns the current position of the file pointer in bytes from the beginning.
Useful for tracking where the file pointer is located.
Syntax:
file.tell()
Example:
f = open("demofile.txt", "r") # Open file in read mode
print(f.tell()) # Prints 0 (File pointer at the start)
f.read(5) # Read first 5 characters
print(f.tell()) # Prints 5 (File pointer moved to 5)
f.close()
Output:
0
5
(Initially, the pointer is at position 0, and after reading 5 characters, it moves to 5.)
Key Differences
Feature seek() tell()
Purpose Moves file pointer to a specific position Returns current file pointer position
Returns Moves pointer, does not return value Returns an integer (byte position)
Use Case Used to jump to specific locations in a file Used to track the file pointer position
Marathi (टीप)
seek(n) – फाईल पॉइीं टर (कसवर) ददलेल्या n स्थानावर हलवतो.
Q6. Write a program function that accepts a string and calculate the number of uppercase
letters and lower case letters.
Ans:-
for char in s:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
# Example Usage
string = input("Enter a string: ")
count_case(string)
Output:
Input:
Enter a string: Hello World!
Output:
Uppercase Letters: 2
Lowercase Letters: 8
Q1. Describe various modes of file object ? Explain any two in detail.
Q2. Explain any four file modes in Python. Q3. List different modes of opening file in python.
(For all three question write the below answer)
Modes of File Handling in Python
• In Python, files can be opened in different modes depending on the required operation. The
programmer needs to specify whether to read ('r'), write ('w'), or append ('a'). Additionally, files can
be opened in text mode ('t') or binary mode ('b').
2. Binary Mode
• The text (t) and binary (b) modes are combined with r, w, or a modes to perform file operations. The
complete list of file modes in Python is shown in the table below:
(IMP : from below 3 program 1 program fix yeto so remember all three )
Q. Write a Python program to read contents from “a.txt” and write same
contents in “b.txt.”
with open('abs.txt','r') as firstfile, open('prq.txt','w') as secondfile:
# read content from first file
for line in firstfile:
# write content to second file
secondfile.write(line)
Q. Write a Python program to read contents of first.txt file and write same
contents in second.txt file..
with open('first.txt', 'r') as f: # Open the first file for reading
contents = f.read() # Read the contents of the file
with open('second.txt', 'w') as f: # Open the second file for writing
f.write(contents) # Write the contents of the first file to the second file
Q. Write a program to open a file in write mode and append some content at
the end of file.
# Append-adds at last
# append mode
file1 = open("myfile.txt", "a")
Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
TodayTomorrow
Exception Handling is a mechanism that helps handle such errors gracefully so that
the program doesn’t crash.
Python provides special keywords like try, except, else, and finally to handle
exceptions properly.
To avoid crashing, we can use try-except to catch the error and display a proper message.
try:
print("Result:", result)
except ZeroDivisionError:
Enter a number: 10
Result: 5.0
Enter a number: 10
Now, the program does not crash! Instead, it shows a friendly error message.
1. try block:
2. except block:
• This block catches the error and prevents the program from crashing.
except ZeroDivisionError:
except ValueError:
else:
finally:
Execution completed!
Execution completed!
The program doesn’t crash, and the finally block still runs.
Execution completed!
Exception Handling म्हणजे कार्यक्रमात र्ेणाऱ्र्ा त्रुटी (errors) िाताळण्याची पद्धत आहे .
try मध्ये त्रुटी येऊ र्कणारा कोड दलदहला जातो.
except मध्ये जर त्रुटी आल्यास, ती योग्य प्रकारे िाताळली जाते आदण प्रोग्राम क्रॅर् होत नाही.
else फक्त त्रुटी नसल्यास चालतो.
finally हा नेिमी चालतो, त्रुटी आली तरी दकींवा आली नाही तरी.
Let's take a real-world example where exception handling is used in an ATM system:
try:
balance = 5000
balance -= withdraw
except ValueError as e:
print("Error:", e)
finally:
Python allows us to define our own exception classes by inheriting from the built-in
Exception class.
The raise keyword is used to trigger a user-defined exception when a condition is met.
• Checking valid passwords (minimum 8 characters, must contain numbers & special
characters).
Python Code:
class InvalidPasswordError(Exception):
self.message = message
super().__init__(self.message)
def check_password(password):
raise InvalidPasswordError()
else:
print("Password is valid!")
try:
check_password(user_password)
except InvalidPasswordError as e:
print("Error:", e)
Output Examples:
Valid Password Case:
Password is valid!
Error: Password is invalid! It must be at least 8 characters long and contain a number &
special character.
User-defined Exception म्हणजे प्रोग्रामरने स्वतः तर्ार केलेली त्रुटी (Error) आिे .
raise कीवडव चा वापर करून आपल्याला गरजेनुसार एरर टाकता येते.
वर ददलेल्या उदाहरणात, पासवडव योग्य नसल्यास InvalidPasswordError नावाची एरर दनमावण
होते.
यात पासवडव 8 कॅरॅ क्टरचा असला पाक्षिजे, नंबर आक्षण स्पेशल कॅरॅ क्टर असावा अर्ी अट
ददली आहे.
अर्ा प्रकारे कस्टम एरर वापरून डे टा व्हॅक्षलडे शन सोपे िोते!
❖ Summer 2022
3. Write a program to open a file in write mode and append some contents at the end
of file (6marks)
❖ Winter 2022
2. Explain how try-catch block is used for exception handling in python. (4marks)
3. Write python program to read contents of abc.txt and write same content to pqr.txt..
(4marks)
❖ Summer 2023
1. With neat example differentiate between readline( ) and readlines( ) functions in file-
handling. (4marks)
❖ Winter 2023
1. State the use of read ( ) and readline ( ) functions in python file handling.. (2marks)
2. Describe various modes of file object ? Explain any two in detail. (4marks)
3. Explain seek ( ) and tell ( ) function for file pointer manipulation in python with
example. (4marks)
4. WAP to read contents of first.txt file and write same content in second.txt file.
(4marks)
❖ Summer 2024
2. Write a program function that accepts a string and calculate the number of uppercase
letters and lower case letters. (4marks)
3. Write a Python program to create user defined exception that will check whether the
password is correct or not. (6marks)
4. Describe various modes of file object. Explain any three in detail. (6marks)
❖ Winter 2024
2. Describe various modes of file object ? Explain any two in details . (4marks)
3. Write python code to check for zero division errors exception . (4marks)
4. Write a Python program to read contents from “a.txt” and write same contents in
“b.txt.” (4marks)
5. Write a Python program to read contents of first.txt file and write same contents in
second.txt file.. (6marks)