0% found this document useful (0 votes)
12 views8 pages

File Haindling in Python Pickle Key

Uploaded by

mgradarshmhss
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)
12 views8 pages

File Haindling in Python Pickle Key

Uploaded by

mgradarshmhss
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

Subject: - Computer Science

Chapter – 2 File Handling in Python


Worksheet

One Mark Questions (Remembering/Understanding Based)

1. State the default mode in which a file is opened using open() function in Python.
Answer: Read mode (r) and in text format.
2. Name the two types of files handled in Python.
Answer: Text files and binary files.
3. Mention one attribute of a file object that returns the access mode.
Answer: [Link]

Two Mark Questions


(Understanding Based)

4. Explain the significance of the End of Line (EOL) character in text files.
Answer: EOL indicates the end of a line in a text file. In Python, the default EOL character is \n.
It helps the interpreter or editor to shift the cursor to a new line when reading the file.

(Application Based)

5. Identify the output of the following code if the file contains the text "Python File":
python
CopyEdit
with open("[Link]", "r") as f:
print([Link](6))

Answer: Python
(Only first 6 characters are read from the file.)

Three Mark Question


(Analytical Based)

6. Compare text and binary files based on readability, use cases, and storage.
Answer:
a. Text files store data in a human-readable form using characters like alphabets and symbols;
binary files store data as byte sequences which are not human-readable.
b. Text files are suitable for storing scripts, CSVs, or logs; binary files store images, audio, video,
etc.
c. Text files are easier to debug and modify, whereas binary files are compact and faster to
process but difficult to edit or correct if corrupted.

Four Mark Question


(Application + Programming Based)

7. Write a Python program that creates a file named [Link], writes the name "Aman" into it, and
then reads and prints the content using the with clause.
Answer:
1
# Writing to the file
with open("[Link]", "w") as f:
[Link]("Aman")

# Reading from the file


with open("[Link]", "r") as f:
content = [Link]()
print(content)

Python Programming Question on File Handling with Exception Handling

8. Write a Python program that:

1. Accepts multiple lines of input from the user and writes them to a file named [Link].
2. Then read and print the content of the file.
3. The program must include exception handling for:
o File not found
o Input/output errors
o Any other unexpected error

Answer:

try:
# Writing to the file
f = open("[Link]", "w")
print("Enter 3 lines of text (press Enter after each line):")
for i in range(3):
line = input()
[Link](line + "\n")
[Link]()

# Reading from the file


f = open("[Link]", "r")
print("\nContents of the file:")
for line in f:
print([Link]())
[Link]()

except FileNotFoundError:
print("Error: File not found.")

except IOError:
print("Error: An I/O error occurred.")

except Exception as e:
print("An unexpected error occurred:", e)

Output (Sample Run):

Enter 3 lines of text (press Enter after each line):


I love Python.
File handling is useful.
2
This is a test.

Contents of the file:


I love Python.
File handling is useful.
This is a test.

Concepts Covered:
 File write and read (write() and for line in file)
 Exception handling using try-except
 Multiple exception types: FileNotFoundError, IOError, Exception

Programming Question (Exception Handling + File Handling)

9. Write a Python program that performs the following tasks:

1. Accepts user data (name and age) and stores it in a file called [Link].
2. The program must handle the following exceptions:
o If the user enters a non-integer age, handle it with a suitable message.
o If there's an error in opening/writing to the file, handle that too.
3. After writing, read and display the contents of the file.

Answer:
python
CopyEdit
try:
# Try to open the file in write mode
file = open("[Link]", "w")

while True:
name = input("Enter your name: ")

try:
age = int(input("Enter your age (in number): "))
except ValueError:
print("❌ Age must be a number. Please try again.")
continue # retry input if invalid age

[Link](f"Name: {name}, Age: {age}\n")

more = input("Do you want to enter more records? (y/n): ")


if [Link]() == 'n':
break

[Link]()

# Reading the file content


print("\n✅ Data successfully written! Now displaying the file content:\n")
file = open("[Link]", "r")
3
print([Link]())
[Link]()

except IOError:
print("❌ An error occurred while handling the file.")

Concepts Used:

 try...except block for handling:


o ValueError for incorrect age input.
o IOError for file handling errors.
 File operations: open in w and r modes.
 Looping with while True and conditional break.

BINARY FILE PROGRAMMING

 Binary File Handling in Python (Using pickle)


Q1 Create a menu-driven program in Python to:
1. Create a binary file named [Link] that stores student records (roll, name, marks).
2. Display all student records.
3. Search for a student by roll number.
4. Update marks of a student by roll number.
Use pickle module for binary file handling.

Answer:# Function to create and write student records

def create_file():
with open("[Link]", "wb") as file:
while True:
roll = int(input("Enter Roll Number: "))
name = input("Enter Name: ")
marks = float(input("Enter Marks: "))
student = [roll, name, marks]
[Link](student, file)
more = input("Add another record? (y/n): ")
if [Link]() != 'y':
break
print("File created successfully.\n")

# Function to display all records


def display_file():
try:
with open("[Link]", "rb") as file:
print("\nAll Student Records:")
while True:
student = [Link](file)
print(f"Roll: {student[0]}, Name: {student[1]}, Marks: {student[2]}")
except EOFError:
pass
except FileNotFoundError:
4
print("File not found!\n")

# Function to search for a record by roll number


def search_record():
found = False
roll_search = int(input("Enter roll number to search: "))
try:
with open("[Link]", "rb") as file:
while True:
student = [Link](file)
if student[0] == roll_search:
print(f"Found: Roll: {student[0]}, Name: {student[1]}, Marks: {student[2]}")
found = True
break
except EOFError:
if not found:
print("Record not found.\n")
except FileNotFoundError:
print("File not found!\n")

# Function to update marks


def update_marks():
updated = False
roll_update = int(input("Enter roll number to update marks: "))
students = []

try:
with open("[Link]", "rb") as file:
while True:
[Link]([Link](file))
except EOFError:
pass
except FileNotFoundError:
print("File not found!\n")
return

with open("[Link]", "wb") as file:


for student in students:
if student[0] == roll_update:
student[2] = float(input("Enter new marks: "))
updated = True
[Link](student, file)

if updated:
print("Marks updated successfully.\n")
else:
print("Record not found.\n")

# Menu-driven interface
while True:
print("1. Create File")
print("2. Display All Records")
print("3. Search Record by Roll Number")
print("4. Update Marks")
print("5. Exit")
5
choice = input("Enter your choice (1-5): ")

if choice == '1':
create_file()
elif choice == '2':
display_file()
elif choice == '3':
search_record()
elif choice == '4':
update_marks()
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number between 1 and 5.")

📘 Key Concepts Covered:

 Binary file creation and reading using [Link]() and [Link]()


 Use of EOFError to detect end of file
 Exception handling (FileNotFoundError)
 Menu-driven approach using loops and conditionals

Q2 Write a Python program to create a binary file [Link] containing records of 3 students. Each
record should store: Roll No, Name, and Marks. Use the pickle module.

Answer:

import pickle

students = [
{"RollNo": 1, "Name": "Ananya", "Marks": 85},
{"RollNo": 2, "Name": "Rohit", "Marks": 92},
{"RollNo": 3, "Name": "Priya", "Marks": 78}
]

with open("[Link]", "wb") as file:


for student in students:
[Link](student, file)

print("Student records written successfully.")

Q3. Write a Python program to display all the records from the binary file [Link].

Answer:

import pickle

with open("[Link]", "rb") as file:


print("Student Records:")
try:
while True:
student = [Link](file)
6
print(student)
except EOFError:
pass

Q4. Write a Python program to search for a student by roll number in the binary file [Link].
Display the student's details if found.

Answer:

import pickle

search_roll = int(input("Enter roll number to search: "))


found = False

with open("[Link]", "rb") as file:


try:
while True:
student = [Link](file)
if student["RollNo"] == search_roll:
print("Student Found:", student)
found = True
break
except EOFError:
if not found:
print("Student not found.")

Q5. Write a Python program to count the number of student records in [Link] whose marks are
more than 80.

Answer:

import pickle
count = 0

with open("[Link]", "rb") as file:


try:
while True:
student = [Link](file)
if student["Marks"] > 80:
count += 1
except EOFError:
pass

print("Number of students with marks > 80:", count)

Q6. Write a Python program to update the marks of a student in [Link] by roll number.

Answer:

import pickle

students = []

# Read all student records into a list


7
with open("[Link]", "rb") as file:
try:
while True:
[Link]([Link](file))
except EOFError:
pass

roll_to_update = int(input("Enter roll number to update marks: "))


new_marks = int(input("Enter new marks: "))

# Update the marks


for student in students:
if student["RollNo"] == roll_to_update:
student["Marks"] = new_marks
print("Marks updated successfully.")

# Rewrite the updated records to the file


with open("[Link]", "wb") as file:
for student in students:
[Link](student, file)

You might also like