SlideShare a Scribd company logo
Contact No - 9568326772
Subject: cs 083
Class 12 – Unit 5 – file handling
Contact No - 9568326772
File Handling in Python
Introduction
Data Files
Opening and Closing Files
Opening Files
Closing Files
Working with Text Files
Reading from Text Files
Writing onto Text Files
The flush() Function
Removing Whitespaces after Reading
File Pointer and Its Role
File Operations:
Reading
Searching
Updating
Writing
Opening Modes
:
Standard Streams
• Standard Input (input())
• Standard Output (print())
• Standard Error
Binary Files
• Open/Close Binary File
• Write (Pickling)
• Read (Unpickling)
• Search & Update Data
CSV Files
• Open/Close CSV File
• Write Data
• Read Data
Contact No - 9568326772
Class 12 – Computer Science with Python
Working with Binary Files
Binary Files
• Open/Close Binary File
• Write (Pickling)
• Read (Unpickling)
• Search & Update Data
Contact No - 9568326772
WORKING WITH BINARY FILES
● Used for writing and reading non-basic Python objects like dictionaries,
lists, or nested lists.
These objects are stored in binary format.
● Pickling
● The process of converting a Python object into a byte stream for storing
in a binary file.
● Unpickling
● The reverse of pickling – converting the byte stream back into the
original Python object.
To use these processes, we use the pickle module in Python.
Pickling = Save object to binary file
Unpickling = Load object from binary file
Contact No - 9568326772
Creating/Opening/Closing Binary Files
•A binary file is opened just like a text file,
but you must add 'b' to the mode to work in binary format.
 p = open("stu.dat", "wb+") # Open for reading and writing (write mode)
 p = open("stu.dat", "rb+") # Open for reading and writing (read mode)
To close the file, use:
 p.close()
Note:
 'wb+' = write + read in binary mode
 'rb+' = read + write in binary mode
Contact No - 9568326772
Writing onto a Binary File – Pickling
You can write Python objects such as dictionaries, tuples, lists, etc., into a
binary file using the pickle module.
Use the dump() function:
pickle.dump(object, file)
Example:
import pickle
my_data = {"name": "Tanmay", "age": 16}
file = open("student.dat", "wb")
pickle.dump(my_data, file)
file.close()
This process of converting an
object into binary format is called
Pickling.
Contact No - 9568326772
Writing onto a Binary File – Pickling
# Step 1: Import the pickle module
import pickle
# Step 2: Create dictionary data for two students
s1 = {'RNo': 101, 'Name': 'Urvashi', 'Age': 18, 'Per': 98.23}
s2 = {'RNo': 102, 'Name': 'Riya', 'Age': 19, 'Per': 97.5}
# Step 3: Open a binary file named 'student.dat' in write mode
with open('student.dat', 'wb') as p:
# Step 4: Store the dictionary data using pickle (pickling process)
pickle.dump(s1, p)
pickle.dump(s2, p)
p.flush() # Forcefully save the data to the file
# Step 5: Show success message
print("Data Inserted Successfully")
Contact No - 9568326772
Binary File Writing using Pickle (with loop)
import pickle
# Open file in write-binary mode
p = open('student.dat', 'wb')
ans = 'y'
while ans.lower() == 'y':
stu = {} # Create a fresh dictionary for each student
rno = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))
stu['Rollno'] = rno
stu['Name'] = name
stu['Marks'] = marks
# Write the student dictionary to file
pickle.dump(stu, p)
ans = input("Want to enter more records? (y/n): ")
# Close the file
p.close()
print("All records saved successfully.")
Notes:
•This code takes input from the user
repeatedly and stores multiple
student records in a binary file.
•Each student's data is saved
separately using the pickle.dump()
method.
•The dictionary stu is re-initialized
inside the loop to avoid overwriting
previous data.
Let me know if you want a version to
read the records back (unpickling).
Contact No - 9568326772
Appending Records in Binary Files
To add (append) new records to an existing
binary file, you should open the file in append
binary mode, i.e., use "ab" or "ab+" mode.
Example Code:
import pickle
stu = {}
p = open('student.dat', 'ab') # Open file in append
binary mode
This allows you to add new data to the file without deleting or
overwriting the existing content.
import pickle
stu = {}
ans = 'y'
# Open the file in append binary mode
with open('student.dat', 'ab') as p:
while ans.lower() == 'y':
rno = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))
# Store data in dictionary
stu['Rollno'] = rno
stu['Name'] = name
stu['Marks'] = marks
# Dump (write) dictionary into file
pickle.dump(stu, p)
# Ask user if they want to add more
ans = input("Want to enter more records? (y/n): ")
print("Records appended successfully.")
Contact No - 9568326772
Reading from a Binary File – UnPickling
Once you have written data to a binary file using the pickle module, you can read
(or load) the data back using the load() function of the pickle module.
<object> = pickle.load(<file_handle>)
Syntax:
Example:
student = pickle.load(fout)
This line will load and return one object (such as a dictionary) that was previously stored in the binary file.
Contact No - 9568326772
Handling EOFError While Using pickle.load()
When reading from a binary file using the pickle module, the load() function raises
EOFError when the end of the file is reached.
To avoid program crashes, we can handle this using:
Method 1: Using try-except block
import pickle
# Open file in read binary mode
with open('student.dat', 'rb') as p:
while True:
try:
data = pickle.load(p)
print(data)
except EOFError:
break
Method 2: Using with statement (also
includes try-except)
import pickle
try:
with open('student.dat', 'rb') as p:
while True:
record = pickle.load(p)
print(record)
except EOFError:
pass
Contact No - 9568326772
(i). Using try and except Blocks
To read from a binary file safely using pickle.load(), you must write it inside try and
except blocks. These help to handle runtime errors like EOFError (End Of File
error).
Explanation:
try block: Contains the code that may generate an exception.
except block: Contains the code to handle the exception if it occurs.
Syntax:
<filehandle> = open(<filename>, <readmode>)
try:
<object> = pickle.load(<filehandle>)
# other processing statements
except EOFError:
<filehandle>.close()
This method ensures that the program doesn’t crash when it reaches the end of the binary file while reading.
Contact No - 9568326772
The with Statement
The with statement is a compact statement which combines the opening of a file and
its processing, along with inbuilt exception handling.
You do not need to mention any exception like EOFError while using the with
statement.
Syntax:
with open(<filename>, <mode>) as <filehandle>:
# use pickle.load
# perform other file manipulation tasks inside this block
This ensures the file is automatically closed after the block is executed, even if an error occurs.
Contact No - 9568326772
Reading from a Binary File
import pickle
stu = {}
p = open('student.dat', 'rb')
try:
while True:
stu = pickle.load(p)
print(stu)
except EOFError:
p.close()
Explanation:
pickle.load() reads one object at a
time.
while True: continues reading until
end of file.
EOFError is raised when all
records are read.
p.close() safely closes the file.
Contact No - 9568326772
Create a Binary File and Write Two Lines of Text
import pickle
# Multi-line text string
text = "This is my first line.nThis is second line."
# Open file in binary write mode and dump the text
with open("myfile.info", "wb") as p:
pickle.dump(text, p)
print("File successfully created.")
Notes:
•n is used to create a new line within the string.
•pickle.dump() writes the string to the file in binary format.
•The file myfile.info will store the text as a pickled object.
Contact No - 9568326772
try:
print("Searching in File student.dat ...")
while True:
stu = pickle.load(p)
if stu['Rollno'] in searchkeys:
print(stu)
found = True
except EOFError:
if found == False:
print("No such records found in the file.")
else:
print("Search successful.")
p.close()
Sequential Search in Binary File (student.dat)
Notes:
 stu['Rollno'] must match the key exactly as
used in the data.
 Make sure 'Rollno' matches the key used
during writing.
 The program searches for roll numbers 101
and 102.
Write a Python program to search for student records in a binary file (student.dat) for
given roll numbers (e.g., 101 or 102). If found, display the records; otherwise, print a
message saying record not found.
import pickle
stu = {}
found = False
p = open('student.dat', 'rb')
searchkeys = [101, 102]
Contact No - 9568326772
Class 12 – Computer Science with Python
Updating in a Binary File in
Python
Contact No - 9568326772
Updating in a Binary File in
Python provides two built-in functions that help in manipulating the file pointer
position in a binary file:
1. tell()
•Returns the current position of the file pointer (in bytes) from the beginning of the
file.
•Useful for tracking where you are in the file.
2. seek(offset)
•Moves the file pointer to a specific position in the file.
•Helps to overwrite or read data from a certain byte location.
Why Use These?
•You may need to search, edit, or update a record without rewriting the whole file.
•These methods help achieve random access in binary files.
Record
Record
Record
Record
Record
Contact No - 9568326772
tell() Function in Python
The tell() function is used to get the current position of the file pointer (in number of
bytes) from the beginning of the file.
It is helpful when you want to know where in the file you are currently reading or writing.
Syntax:
file_pointer.tell()
Example:
p = open("sample.txt", "r")
print("Default position is:", p.tell()) # Shows starting position
print("Reading 3 bytes:", p.read(3)) # Reads first 3 characters
print("Now the file-pointer location is:", p.tell()) # Shows position after reading
p.close()
Output (if file has enough content):
Default position is: 0
Reading 3 bytes: Thi
Now the file-pointer location is: 3
Contact No - 9568326772
seek() Function in Python
The seek() function is used to move the file pointer to a specific position in a file.
It helps in reading or writing data at any desired location in the file.
Syntax:
<file-object>.seek(offset[, mode])
 Parameters:
 Offset:
A number that specifies the number of bytes to move the file pointer.
 Mode:
A number that determines from where to move:
 0 → from beginning of the file
 1 → from current position
 2 → from end of the file
 File object:
The handle of the opened file (e.g., p in p.seek()).
p.seek(50, 0) # Move to 50th byte from the beginning
p.seek(-5, 1) # Move 5 bytes back from current position
p.seek(-15, 2) # Move to 15 bytes before end of file
Contact No - 9568326772
Example:
p = open("sample.txt", "rb")
p.seek(50, 0) # Moves 50 bytes from the start of file
p.seek(-5, 1) # Moves 5 bytes back from current position
p.seek(-15, 2) # Moves 15 bytes before the end of file
p.close()
Notes:
•Use "rb" or "wb" mode while using seek() with 1 or 2.
•Negative offset only works in binary mode and with modes 1 or 2.
Contact No - 9568326772
# Open file in binary mode
p = open("sample.txt", "rb")
# Move the pointer 15 bytes before the end of the file
p.seek(-15, 2)
# Read 15 bytes
text = p.read(15)
# Decode bytes to string for printing
print("Last 15 bytes of file contain:", text.decode())
# Close the file
p.close()
Read the Last 15 Bytes of the File "sample.txt"
Why binary mode is
needed?
•seek() with negative values
works only in binary mode
('rb').
•Text mode ('r') doesn’t allow
seeking backwards from the
end.
Contact No - 9568326772
Updating Record(s) in a File
import pickle
found = False
p = open('student.dat', 'rb+')
try:
while True:
rpos = p.tell() # Save current file pointer position
stu = pickle.load(p) # Load the record
if stu['Marks'] >= 50: # Check condition
stu['Marks'] += 2 # Update the marks
p.seek(rpos) # Move file pointer back to
record's position
pickle.dump(stu, p) # Overwrite with updated
record
found = True
except EOFError:
if not found:
print("No such records found in the file.")
else:
print("Successfully updated record(s).")
finally:
p.close()
Contact No - 9568326772
Class 12 – Computer Science with Python
(Working with CSV Files)
CSV stands for Comma Separated
Values.
Contact No - 9568326772
CSV Files – Why Are They Popular?
● CSV (Comma Separated Values) files are widely used due to the following
reasons:
● Easy to Create
Simple to Export and Import
Compatible with Databases and Spreadsheets
Good for storing structured tabular data
Marks
Name
Roll No
89
Tanmay
101
93
Urvasgi
102
76
Riya
103
82
Ansh
104
95
Kritika
105
Contact No - 9568326772
What is a CSV File?
CSV (Comma-Separated Values) files store tabular data in plain text.
Each line in a CSV file is a row, and values are separated by a delimiter.
The default delimiter is a comma (,).
Other delimiters can be:
Tab (t)
Colon (:)
Pipe (|)
Semicolon (;)
Python csv Module
Python has a built-in csv module for working with CSV files.
It provides two main objects:
csv.reader – for reading CSV files
csv.writer – for writing to CSV files
Import the module using:
import csv
Contact No - 9568326772
Opening & Closing CSV Files
1. Use .csv Extension
Always save your CSV file with the .csv extension.
Example: "empdata.csv"
2. Open Like a Text File
Use open() function to open the file.
p = open("empdata.csv", "w") # 'w' means write mode
3. Close the File
Use the close() function to close the file.
p.close()
Contact No - 9568326772
import csv
# Open the CSV file in write mode
p = open("demo.csv", "w", newline="")
# Create CSV writer object
empdata = csv.writer(p)
# Write header row
empdata.writerow(['Empid', 'Name', 'Salary'])
# Input and write 5 employee records
for i in range(5):
print("Employee Record", i + 1)
empid = int(input("Enter Id: "))
empname = input("Enter Name: ")
empsalary = int(input("Enter Salary: "))
# Create a list for one record
emprec = [empid, empname, empsalary]
# Write the record to the file
empdata.writerow(emprec)
# Close the file
p.close()
print("CSV file created successfully!")
Writing Rows to a CSV File Using writerow()
Contact No - 9568326772
CSV File Writing Example for Students
import csv # Import the csv module
# Step 1: Open a new CSV file in write mode
file = open("student_data.csv", "w", newline="")
# Step 2: Create a CSV writer object
writer = csv.writer(file)
# Step 3: Write column headings
writer.writerow(['Roll No', 'Name', 'Marks'])
# Step 4: Take input of 5 student records
for i in range(5):
print("Enter details of Student", i + 1)
rollno = int(input("Enter Roll No: "))
name = input("Enter Name: ")
marks = float(input("Enter Marks: "))
# Store one student's data in a list
student_record = [rollno, name, marks]
# Step 5: Write the record to the CSV file
writer.writerow(student_record)
# Step 6: Close the file
file.close()
print(" Student data saved successfully in CSV file!")
Contact No - 9568326772
Contact No - 9568326772
You're very welcome!
Thank You!

More Related Content

PPTX
File handling in Python
PPTX
Binary_File_Handling_Themed_Class12_CS.pptx
PDF
5.1 Binary File Handling.pdf
PPTX
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
PPTX
Binary File.pptx
PDF
File handling with python class 12th .pdf
PPTX
file handling in python using exception statement
PPTX
BINARY files CSV files JSON files with example.pptx
File handling in Python
Binary_File_Handling_Themed_Class12_CS.pptx
5.1 Binary File Handling.pdf
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
Binary File.pptx
File handling with python class 12th .pdf
file handling in python using exception statement
BINARY files CSV files JSON files with example.pptx

Similar to class 12 Unit 5 file handling.pdf skhnjhn (20)

PPTX
01 file handling for class use class pptx
PPT
File Handling Btech computer science and engineering ppt
PPTX
File handling in python basics for class 12 CBSE
PPTX
Python data file handling
PPTX
File Handling in Python -binary files.pptx
PPTX
FILE HANDLING.pptx
PPTX
Chapter 08 data file handling
PDF
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
PPTX
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
PPTX
Data File Handling in Python Programming
PPTX
DFH PDF-converted.pptx
PPTX
FILE HANDLING in python to understand basic operations.
PDF
Python programming : Files
PPTX
file handling.pptx avlothaan pa thambi popa
PPTX
file handlling in python 23.12.24 geetha.pptx
PPTX
files.pptx
PPTX
FILE HANDLING IN PYTHON Presentation Computer Science
PDF
Python Programming - XII. File Processing
PPT
File Handling as 08032021 (1).ppt
PPTX
FILE INPUT OUTPUT.pptx
01 file handling for class use class pptx
File Handling Btech computer science and engineering ppt
File handling in python basics for class 12 CBSE
Python data file handling
File Handling in Python -binary files.pptx
FILE HANDLING.pptx
Chapter 08 data file handling
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
Data File Handling in Python Programming
DFH PDF-converted.pptx
FILE HANDLING in python to understand basic operations.
Python programming : Files
file handling.pptx avlothaan pa thambi popa
file handlling in python 23.12.24 geetha.pptx
files.pptx
FILE HANDLING IN PYTHON Presentation Computer Science
Python Programming - XII. File Processing
File Handling as 08032021 (1).ppt
FILE INPUT OUTPUT.pptx
Ad

Recently uploaded (20)

PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Cell Types and Its function , kingdom of life
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Institutional Correction lecture only . . .
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Presentation on HIE in infants and its manifestations
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Microbial diseases, their pathogenesis and prophylaxis
Final Presentation General Medicine 03-08-2024.pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Cell Types and Its function , kingdom of life
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Institutional Correction lecture only . . .
Computing-Curriculum for Schools in Ghana
Presentation on HIE in infants and its manifestations
Final Presentation General Medicine 03-08-2024.pptx
O7-L3 Supply Chain Operations - ICLT Program
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
VCE English Exam - Section C Student Revision Booklet
102 student loan defaulters named and shamed – Is someone you know on the list?
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Pharma ospi slides which help in ospi learning
Microbial diseases, their pathogenesis and prophylaxis
Ad

class 12 Unit 5 file handling.pdf skhnjhn

  • 1. Contact No - 9568326772 Subject: cs 083 Class 12 – Unit 5 – file handling
  • 2. Contact No - 9568326772 File Handling in Python Introduction Data Files Opening and Closing Files Opening Files Closing Files Working with Text Files Reading from Text Files Writing onto Text Files The flush() Function Removing Whitespaces after Reading File Pointer and Its Role File Operations: Reading Searching Updating Writing Opening Modes : Standard Streams • Standard Input (input()) • Standard Output (print()) • Standard Error Binary Files • Open/Close Binary File • Write (Pickling) • Read (Unpickling) • Search & Update Data CSV Files • Open/Close CSV File • Write Data • Read Data
  • 3. Contact No - 9568326772 Class 12 – Computer Science with Python Working with Binary Files Binary Files • Open/Close Binary File • Write (Pickling) • Read (Unpickling) • Search & Update Data
  • 4. Contact No - 9568326772 WORKING WITH BINARY FILES ● Used for writing and reading non-basic Python objects like dictionaries, lists, or nested lists. These objects are stored in binary format. ● Pickling ● The process of converting a Python object into a byte stream for storing in a binary file. ● Unpickling ● The reverse of pickling – converting the byte stream back into the original Python object. To use these processes, we use the pickle module in Python. Pickling = Save object to binary file Unpickling = Load object from binary file
  • 5. Contact No - 9568326772 Creating/Opening/Closing Binary Files •A binary file is opened just like a text file, but you must add 'b' to the mode to work in binary format.  p = open("stu.dat", "wb+") # Open for reading and writing (write mode)  p = open("stu.dat", "rb+") # Open for reading and writing (read mode) To close the file, use:  p.close() Note:  'wb+' = write + read in binary mode  'rb+' = read + write in binary mode
  • 6. Contact No - 9568326772 Writing onto a Binary File – Pickling You can write Python objects such as dictionaries, tuples, lists, etc., into a binary file using the pickle module. Use the dump() function: pickle.dump(object, file) Example: import pickle my_data = {"name": "Tanmay", "age": 16} file = open("student.dat", "wb") pickle.dump(my_data, file) file.close() This process of converting an object into binary format is called Pickling.
  • 7. Contact No - 9568326772 Writing onto a Binary File – Pickling # Step 1: Import the pickle module import pickle # Step 2: Create dictionary data for two students s1 = {'RNo': 101, 'Name': 'Urvashi', 'Age': 18, 'Per': 98.23} s2 = {'RNo': 102, 'Name': 'Riya', 'Age': 19, 'Per': 97.5} # Step 3: Open a binary file named 'student.dat' in write mode with open('student.dat', 'wb') as p: # Step 4: Store the dictionary data using pickle (pickling process) pickle.dump(s1, p) pickle.dump(s2, p) p.flush() # Forcefully save the data to the file # Step 5: Show success message print("Data Inserted Successfully")
  • 8. Contact No - 9568326772 Binary File Writing using Pickle (with loop) import pickle # Open file in write-binary mode p = open('student.dat', 'wb') ans = 'y' while ans.lower() == 'y': stu = {} # Create a fresh dictionary for each student rno = int(input("Enter roll number: ")) name = input("Enter name: ") marks = float(input("Enter marks: ")) stu['Rollno'] = rno stu['Name'] = name stu['Marks'] = marks # Write the student dictionary to file pickle.dump(stu, p) ans = input("Want to enter more records? (y/n): ") # Close the file p.close() print("All records saved successfully.") Notes: •This code takes input from the user repeatedly and stores multiple student records in a binary file. •Each student's data is saved separately using the pickle.dump() method. •The dictionary stu is re-initialized inside the loop to avoid overwriting previous data. Let me know if you want a version to read the records back (unpickling).
  • 9. Contact No - 9568326772 Appending Records in Binary Files To add (append) new records to an existing binary file, you should open the file in append binary mode, i.e., use "ab" or "ab+" mode. Example Code: import pickle stu = {} p = open('student.dat', 'ab') # Open file in append binary mode This allows you to add new data to the file without deleting or overwriting the existing content. import pickle stu = {} ans = 'y' # Open the file in append binary mode with open('student.dat', 'ab') as p: while ans.lower() == 'y': rno = int(input("Enter roll number: ")) name = input("Enter name: ") marks = float(input("Enter marks: ")) # Store data in dictionary stu['Rollno'] = rno stu['Name'] = name stu['Marks'] = marks # Dump (write) dictionary into file pickle.dump(stu, p) # Ask user if they want to add more ans = input("Want to enter more records? (y/n): ") print("Records appended successfully.")
  • 10. Contact No - 9568326772 Reading from a Binary File – UnPickling Once you have written data to a binary file using the pickle module, you can read (or load) the data back using the load() function of the pickle module. <object> = pickle.load(<file_handle>) Syntax: Example: student = pickle.load(fout) This line will load and return one object (such as a dictionary) that was previously stored in the binary file.
  • 11. Contact No - 9568326772 Handling EOFError While Using pickle.load() When reading from a binary file using the pickle module, the load() function raises EOFError when the end of the file is reached. To avoid program crashes, we can handle this using: Method 1: Using try-except block import pickle # Open file in read binary mode with open('student.dat', 'rb') as p: while True: try: data = pickle.load(p) print(data) except EOFError: break Method 2: Using with statement (also includes try-except) import pickle try: with open('student.dat', 'rb') as p: while True: record = pickle.load(p) print(record) except EOFError: pass
  • 12. Contact No - 9568326772 (i). Using try and except Blocks To read from a binary file safely using pickle.load(), you must write it inside try and except blocks. These help to handle runtime errors like EOFError (End Of File error). Explanation: try block: Contains the code that may generate an exception. except block: Contains the code to handle the exception if it occurs. Syntax: <filehandle> = open(<filename>, <readmode>) try: <object> = pickle.load(<filehandle>) # other processing statements except EOFError: <filehandle>.close() This method ensures that the program doesn’t crash when it reaches the end of the binary file while reading.
  • 13. Contact No - 9568326772 The with Statement The with statement is a compact statement which combines the opening of a file and its processing, along with inbuilt exception handling. You do not need to mention any exception like EOFError while using the with statement. Syntax: with open(<filename>, <mode>) as <filehandle>: # use pickle.load # perform other file manipulation tasks inside this block This ensures the file is automatically closed after the block is executed, even if an error occurs.
  • 14. Contact No - 9568326772 Reading from a Binary File import pickle stu = {} p = open('student.dat', 'rb') try: while True: stu = pickle.load(p) print(stu) except EOFError: p.close() Explanation: pickle.load() reads one object at a time. while True: continues reading until end of file. EOFError is raised when all records are read. p.close() safely closes the file.
  • 15. Contact No - 9568326772 Create a Binary File and Write Two Lines of Text import pickle # Multi-line text string text = "This is my first line.nThis is second line." # Open file in binary write mode and dump the text with open("myfile.info", "wb") as p: pickle.dump(text, p) print("File successfully created.") Notes: •n is used to create a new line within the string. •pickle.dump() writes the string to the file in binary format. •The file myfile.info will store the text as a pickled object.
  • 16. Contact No - 9568326772 try: print("Searching in File student.dat ...") while True: stu = pickle.load(p) if stu['Rollno'] in searchkeys: print(stu) found = True except EOFError: if found == False: print("No such records found in the file.") else: print("Search successful.") p.close() Sequential Search in Binary File (student.dat) Notes:  stu['Rollno'] must match the key exactly as used in the data.  Make sure 'Rollno' matches the key used during writing.  The program searches for roll numbers 101 and 102. Write a Python program to search for student records in a binary file (student.dat) for given roll numbers (e.g., 101 or 102). If found, display the records; otherwise, print a message saying record not found. import pickle stu = {} found = False p = open('student.dat', 'rb') searchkeys = [101, 102]
  • 17. Contact No - 9568326772 Class 12 – Computer Science with Python Updating in a Binary File in Python
  • 18. Contact No - 9568326772 Updating in a Binary File in Python provides two built-in functions that help in manipulating the file pointer position in a binary file: 1. tell() •Returns the current position of the file pointer (in bytes) from the beginning of the file. •Useful for tracking where you are in the file. 2. seek(offset) •Moves the file pointer to a specific position in the file. •Helps to overwrite or read data from a certain byte location. Why Use These? •You may need to search, edit, or update a record without rewriting the whole file. •These methods help achieve random access in binary files. Record Record Record Record Record
  • 19. Contact No - 9568326772 tell() Function in Python The tell() function is used to get the current position of the file pointer (in number of bytes) from the beginning of the file. It is helpful when you want to know where in the file you are currently reading or writing. Syntax: file_pointer.tell() Example: p = open("sample.txt", "r") print("Default position is:", p.tell()) # Shows starting position print("Reading 3 bytes:", p.read(3)) # Reads first 3 characters print("Now the file-pointer location is:", p.tell()) # Shows position after reading p.close() Output (if file has enough content): Default position is: 0 Reading 3 bytes: Thi Now the file-pointer location is: 3
  • 20. Contact No - 9568326772 seek() Function in Python The seek() function is used to move the file pointer to a specific position in a file. It helps in reading or writing data at any desired location in the file. Syntax: <file-object>.seek(offset[, mode])  Parameters:  Offset: A number that specifies the number of bytes to move the file pointer.  Mode: A number that determines from where to move:  0 → from beginning of the file  1 → from current position  2 → from end of the file  File object: The handle of the opened file (e.g., p in p.seek()). p.seek(50, 0) # Move to 50th byte from the beginning p.seek(-5, 1) # Move 5 bytes back from current position p.seek(-15, 2) # Move to 15 bytes before end of file
  • 21. Contact No - 9568326772 Example: p = open("sample.txt", "rb") p.seek(50, 0) # Moves 50 bytes from the start of file p.seek(-5, 1) # Moves 5 bytes back from current position p.seek(-15, 2) # Moves 15 bytes before the end of file p.close() Notes: •Use "rb" or "wb" mode while using seek() with 1 or 2. •Negative offset only works in binary mode and with modes 1 or 2.
  • 22. Contact No - 9568326772 # Open file in binary mode p = open("sample.txt", "rb") # Move the pointer 15 bytes before the end of the file p.seek(-15, 2) # Read 15 bytes text = p.read(15) # Decode bytes to string for printing print("Last 15 bytes of file contain:", text.decode()) # Close the file p.close() Read the Last 15 Bytes of the File "sample.txt" Why binary mode is needed? •seek() with negative values works only in binary mode ('rb'). •Text mode ('r') doesn’t allow seeking backwards from the end.
  • 23. Contact No - 9568326772 Updating Record(s) in a File import pickle found = False p = open('student.dat', 'rb+') try: while True: rpos = p.tell() # Save current file pointer position stu = pickle.load(p) # Load the record if stu['Marks'] >= 50: # Check condition stu['Marks'] += 2 # Update the marks p.seek(rpos) # Move file pointer back to record's position pickle.dump(stu, p) # Overwrite with updated record found = True except EOFError: if not found: print("No such records found in the file.") else: print("Successfully updated record(s).") finally: p.close()
  • 24. Contact No - 9568326772 Class 12 – Computer Science with Python (Working with CSV Files) CSV stands for Comma Separated Values.
  • 25. Contact No - 9568326772 CSV Files – Why Are They Popular? ● CSV (Comma Separated Values) files are widely used due to the following reasons: ● Easy to Create Simple to Export and Import Compatible with Databases and Spreadsheets Good for storing structured tabular data Marks Name Roll No 89 Tanmay 101 93 Urvasgi 102 76 Riya 103 82 Ansh 104 95 Kritika 105
  • 26. Contact No - 9568326772 What is a CSV File? CSV (Comma-Separated Values) files store tabular data in plain text. Each line in a CSV file is a row, and values are separated by a delimiter. The default delimiter is a comma (,). Other delimiters can be: Tab (t) Colon (:) Pipe (|) Semicolon (;) Python csv Module Python has a built-in csv module for working with CSV files. It provides two main objects: csv.reader – for reading CSV files csv.writer – for writing to CSV files Import the module using: import csv
  • 27. Contact No - 9568326772 Opening & Closing CSV Files 1. Use .csv Extension Always save your CSV file with the .csv extension. Example: "empdata.csv" 2. Open Like a Text File Use open() function to open the file. p = open("empdata.csv", "w") # 'w' means write mode 3. Close the File Use the close() function to close the file. p.close()
  • 28. Contact No - 9568326772 import csv # Open the CSV file in write mode p = open("demo.csv", "w", newline="") # Create CSV writer object empdata = csv.writer(p) # Write header row empdata.writerow(['Empid', 'Name', 'Salary']) # Input and write 5 employee records for i in range(5): print("Employee Record", i + 1) empid = int(input("Enter Id: ")) empname = input("Enter Name: ") empsalary = int(input("Enter Salary: ")) # Create a list for one record emprec = [empid, empname, empsalary] # Write the record to the file empdata.writerow(emprec) # Close the file p.close() print("CSV file created successfully!") Writing Rows to a CSV File Using writerow()
  • 29. Contact No - 9568326772 CSV File Writing Example for Students import csv # Import the csv module # Step 1: Open a new CSV file in write mode file = open("student_data.csv", "w", newline="") # Step 2: Create a CSV writer object writer = csv.writer(file) # Step 3: Write column headings writer.writerow(['Roll No', 'Name', 'Marks']) # Step 4: Take input of 5 student records for i in range(5): print("Enter details of Student", i + 1) rollno = int(input("Enter Roll No: ")) name = input("Enter Name: ") marks = float(input("Enter Marks: ")) # Store one student's data in a list student_record = [rollno, name, marks] # Step 5: Write the record to the CSV file writer.writerow(student_record) # Step 6: Close the file file.close() print(" Student data saved successfully in CSV file!")
  • 30. Contact No - 9568326772
  • 31. Contact No - 9568326772 You're very welcome! Thank You!