2nd pu notes

2nd PUC Computer Science File Handling in Python Notes | Class 12 Chapter

Venkatesh A August 20, 2026 28 min read
2nd PUC Computer Science File Handling in Python Notes | Class 12 Chapter 2
2nd PUC / Class XII Computer Science Chapter 2

Complete Short Notes & Exam Preparation Guide

Complete chapter notes based on the NCERT Class XII Computer Science textbook chapter.

verakworld.com

πŸ“š Chapter Overview

Earlier Python programs accept input, manipulate it and display output. Such input and output are normally available only while the program is executing. Variables used by a program have a lifetime that lasts while the program is under execution.

To store input data and generated output permanently for later reuse, data can be stored on secondary storage devices in files. Python programs written in script mode are stored with the .py extension. Similarly, data entered and output generated can also be stored permanently in files.

Definition of a File: A file is a named location on a secondary storage media where data are permanently stored for later access.
verakworld.com

πŸ“– Table of Contents

  1. Types of Files
  2. Text File
  3. Binary Files
  4. Opening and Closing a Text File
  5. File Open Modes
  6. Closing a File
  7. Opening a File Using with Clause
  8. Writing to a Text File
  9. Reading from a Text File
  10. Setting Offsets in a File
  11. Creating and Traversing a Text File
  12. The Pickle Module
  13. Quick Revision
  14. Important Questions
verakworld.com

2.2 Types of Files

Computers store every file as a collection of 0s and 1s, that is, in binary form. Therefore, every file is basically a series of bytes stored one after the other.

There are mainly two types of data files:

Text File

A text file consists of human-readable characters and can be opened using a text editor.

Binary File

A binary file consists of non-human-readable characters and symbols and requires specific programs to access its contents.

verakworld.com

2.2.1 Text File

A text file can be understood as a sequence of characters consisting of alphabets, numbers and other special symbols.

Examples of text-file extensions mentioned in the chapter include: .txt, .py and .csv.

When a text file is opened using a text editor such as Notepad, several lines of text are displayed. Internally, however, the contents are stored as a sequence of bytes consisting of 0s and 1s.

In ASCII, UNICODE or another encoding scheme, the value of each character of the text file is stored as bytes. The text editor translates the character value and displays the corresponding readable character.

Example: The ASCII value 65, whose binary equivalent is 1000001, is displayed as the letter A because 65 represents A in the ASCII character set.

End of Line (EOL)

Each line of a text file is terminated by a special character called the End of Line (EOL). The default EOL character in Python is the newline character \n.

Contents in a text file are usually separated by whitespace. Comma , and tab \t are also commonly used to separate values.

Activity 2.1 β€” File Size Comparison

Create a text file using Notepad, write your name and save it. Then create a .docx file using Microsoft Word, write your name and save it. Compare the file sizes.

The chapter explains that the size of the .txt file is in bytes, whereas the size of the .docx file is in KBs.

A text file contains the ASCII equivalent of its contents, whereas a .docx file contains additional information such as author’s name, page settings, font type and size, and creation and modification dates.

verakworld.com

2.2.2 Binary Files

Binary files are also stored in terms of bytes, but unlike text files, these bytes do not represent ASCII values of characters. Instead, they represent the actual content such as images, audio, video, compressed versions of other files and executable files.

Binary files are not human readable. Trying to open a binary file using a text editor may display garbage values. Specific software is required to read or write their contents.

  • Binary files are stored as a sequence of bytes.
  • Even a single bit change can corrupt a binary file and make it unreadable to the supporting application.
  • Errors in binary files are difficult to remove because the stored contents are not human readable.
  • Python programs can read and write both text and binary files.
verakworld.com

2.3 Opening and Closing a Text File

In real-world applications, computer programs deal with data from sources such as databases, CSV files, HTML, XML and JSON.

Files can broadly be accessed to write or read data. File operations include creating and opening a file, writing data, traversing a file and reading data.

Python has the io module containing functions for handling files.

2.3.1 Opening a File

Python uses the open() function to open a file.

Syntax
file_object = open(file_name, access_mode)

The function returns a file object called a file handle. This object is stored in the variable file_object and can be used to transfer data to and from the file by calling functions defined in Python’s io module.

If the specified file does not exist, the statement creates a new empty file and assigns it the specified name.

File Object Attributes

Attribute Meaning
<file.closed> Returns true if the file is closed and false otherwise.
<file.mode> Returns the access mode in which the file was opened.
<file.name> Returns the name of the file.

The file_name is the name of the file to be opened. If the file is not in the current working directory, its complete path along with its name needs to be specified.

The access_mode is an optional argument that represents the mode in which the file is accessed. It is also called processing mode.

Examples include r for reading, w for writing, + for both reading and writing, and a for appending at the end of an existing file.

The default mode is read mode. A file can also be handled in binary mode using b or text mode. By default, files are opened in text mode.

Exam Point: Remember that open() returns a file object/file handle and the access mode specifies the operation for which the file is opened.
verakworld.com

Table 2.1 β€” File Open Modes

File Mode Description File Offset Position
r Opens the file in read-only mode. Beginning of the file
rb Opens the file in binary and read-only mode. Beginning of the file
r+ or +r Opens the file in both read and write mode. Beginning of the file
w Opens the file in write mode. If the file already exists, its contents are overwritten. If it does not exist, a new file is created. Beginning of the file
wb+ or +wb Opens the file in read, write and binary mode. Existing contents are overwritten; if the file does not exist, a new file is created. Beginning of the file
a Opens the file in append mode. If the file does not exist, a new file is created. End of the file
a+ or +a Opens the file in append and read mode. If the file does not exist, it creates a new file. End of the file

Example

myObject=open("myfile.txt", "a+")

Here, myfile.txt is opened in append and read modes. The file object is at the end of the file. Therefore, data can be written at the end and data can also be read from the file using the file object named myObject.

Activity 2.2: Other file access modes mentioned in the chapter are rb+, wb, w+, ab and ab+. The chapter asks students to find their purposes and file offset positions.
verakworld.com

2.3.2 Closing a File

After completing read/write operations, it is good practice to close the file. Python provides the close() method.

Syntax
file_object.close()

Here, file_object is the object returned while opening the file.

When a file is closed, the system frees the memory allocated to it. Python also makes sure that unwritten or unsaved data is flushed and written to the file before it is closed.

Therefore, it is advised to close the file after completing the work. If the file object is reassigned to another file, the previous file is automatically closed.

verakworld.com

2.3.3 Opening a File Using with Clause

Python also allows a file to be opened using the with clause.

Syntax
with open(file_name, access_mode) as file_object:

A file opened using the with clause is closed automatically when control comes outside the with clause.

If the user forgets to close the file explicitly or an exception occurs, the file is closed automatically. The syntax is also simpler.

Example from the chapter
with open("myfile.txt","r+") as myObject:
    content = myObject.read()

In this example, the file does not have to be closed explicitly using close(); Python automatically closes it.

Exam Point: The major advantage of the with clause is automatic closing of the opened file.
verakworld.com

2.4 Writing to a Text File

For writing to a file, the file must first be opened in write or append mode.

If an existing file is opened in write mode, its previous data is erased and the file object is positioned at the beginning. In append mode, new data is added at the end because the file object is at the end of the previous data.

The following methods are used to write data:

Method Purpose
write() Writes a single string.
writelines() Writes a sequence of strings.

2.4.1 The write() Method

The write() method takes a string as an argument and writes it to the text file. It returns the number of characters written during that execution.

A newline character \n needs to be added at the end of each sentence to mark the end of a line.

Example
>>> myobject=open("myfile.txt",'w')
>>> myobject.write("Hey I have started
#using files in Python\n")
41
>>> myobject.close()

The write() method returns 41 because that is the length of the string passed as the argument.

Note: \n is treated as a single character.

Writing Numeric Data

If numeric data is to be written to a text file, it must first be converted into a string.

>>>myobject=open("myfile.txt",'w')
>>> marks=58
#number 58 is converted to a string using
#str()
>>> myobject.write(str(marks))
2
>>>myobject.close()

The write() method actually writes data to a buffer. When close() is executed, the contents of the buffer are moved to the file located on permanent storage.

2.4.2 The writelines() Method

The writelines() method is used to write multiple strings to a file. An iterable object such as a list or tuple containing strings is passed to it.

Unlike write(), writelines() does not return the number of characters written.

Example
>>> myobject=open("myfile.txt",'w')
>>> lines = ["Hello everyone\n", "Writing
#multiline strings\n", "This is the
#third line"]
>>> myobject.writelines(lines)
>>>myobject.close()

When the file is opened, its contents appear as the three lines written by the program.

The chapter also mentions the flush() method, which can be used to clear the buffer and write its contents to the file. It allows programmers to forcefully write the contents in the buffer when required.
verakworld.com

2.5 Reading from a Text File

A file can be read after opening it in r, r+, w+ or a+ mode.

The chapter explains three ways to read the contents of a file:

1. read()

Reads a specified number of bytes or the entire file when no argument/negative number is given.

2. readline()

Reads a line from a file, with an optional number of bytes up to the newline.

3. readlines()

Reads all lines and returns them as a list of strings.

2.5.1 The read() Method

The read() method is used to read a specified number of bytes of data from a data file.

Syntax
file_object.read(n)
Example
>>>myobject=open("myfile.txt",'r')
>>> myobject.read(10)
'Hello ever'
>>> myobject.close()

If no argument or a negative number is specified, the entire file content is read.

>>> myobject=open("myfile.txt",'r')
>>> print(myobject.read())
Hello everyone
Writing multiline strings
This is the third line
>>> myobject.close()

2.5.2 The readline([n]) Method

The readline([n]) method reads one complete line from a file where each line ends with the newline character \n.

It can also read a specified number n of bytes from a line, but the reading stops at the newline character.

>>> myobject=open("myfile.txt",'r')
>>> myobject.readline(10)
'Hello ever'
>>> myobject.close()

If no argument or a negative number is specified, it reads a complete line and returns it as a string.

>>>myobject=open("myfile.txt",'r')
>>> print (myobject.readline())
'Hello everyone\n'

To read an entire file line by line using readline(), a loop can be used. This is called looping/iterating over a file object. It returns an empty string when EOF is reached.

2.5.3 The readlines() Method

The readlines() method reads all lines and returns the lines along with newline characters as a list of strings.

>>> myobject=open("myfile.txt", 'r')
>>> print(myobject.readlines())
['Hello everyone\n', 'Writing multiline
strings\n', 'This is the third line']
>>> myobject.close()

When a file is read using readlines(), each line becomes a member of a list and each list element ends with a newline character \n.

split() and splitlines()

The chapter demonstrates that split() can be used to display each word of a line separately as elements of a list.

>>> for line in d:
    words=line.split()
    print(words)

['Hello', 'everyone']
['Writing', 'multiline', 'strings']
['This', 'is', 'the', 'third', 'line']

With splitlines(), each line is returned as an element of a list.

>>> for line in d:
    words=line.splitlines()
    print(words)

['Hello everyone']
['Writing multiline strings']
['This is the third line']
Important Difference: readline() reads one line at a time, whereas readlines() reads all lines and returns them as a list of strings.
verakworld.com

Program 2-1 β€” Writing and Reading to a Text File

fobject=open("testfile.txt","w") # creating a data file
sentence=input("Enter the contents to be written in the file: ")
fobject.write(sentence) # Writing data to the file
fobject.close() # Closing a file
print("Now reading the contents of the file: ")
fobject=open("testfile.txt","r")
#looping over the file object to read the file
for str in fobject: 
    print(str)
fobject.close()

Explanation

The file testfile.txt is opened in write mode and the file handle fobject is returned. A string is accepted from the user and written to the file using write().

The file is then closed and opened again in read mode. Data is read from the file and displayed until the end of the file is reached.

Output of Program 2-1

>>>
RESTART: Path_to_file\Program2-1.py
Enter the contents to be written in the file:
roll_numbers = [1, 2, 3, 4, 5, 6]
Now reading the contents of the file:
roll_numbers = [1, 2, 3, 4, 5, 6]
>>>
verakworld.com

2.6 Setting Offsets in a File

The functions discussed so far access data sequentially. Python provides seek() and tell() when data needs to be accessed in a random fashion.

2.6.1 The tell() Method

The tell() function returns an integer specifying the current position of the file object in the file.

The position is the byte position from the beginning of the file up to the current position of the file object.

Syntax
file_object.tell()

2.6.2 The seek() Method

The seek() method positions the file object at a particular position in a file.

Syntax
file_object.seek(offset [, reference_point])
Reference Point Meaning
0 Beginning of the file
1 Current position of the file
2 End of file

By default, reference_point is 0, so the offset is counted from the beginning of the file.

For example, fileObject.seek(5,0) positions the file object at the 5th byte position from the beginning of the file.

Beginning
0
β†’
Current
1
β†’
End
2
verakworld.com
verakworld.com

Program 2-2 β€” Application of seek() and tell()

print("Learning to move the fi le object")
fi leobject=open("testfi le.txt","r+")
str=fi leobject.read()
print(str)
print("Initially, the position of the fi le object is: ",fi leobject.tell())
fi leobject.seek(0)
print("Now the fi le object is at the beginning of the fi le: ",
      fi leobject.tell())
fi leobject.seek(10)
print("We are moving to 10th byte position from the beginning of fi le")
print("The position of the fi le object is at", fi leobject.tell())
str=fi leobject.read()
print(str)

Output of Program 2-2

>>>
RESTART: Path_to_fi le\Program2-2.py
Learning to move the fi le object
roll_numbers = [1, 2, 3, 4, 5, 6]
Initially, the position of the fi le object is: 33
Now the fi le object is at the beginning of the fi le: 0
We are moving to 10th byte position from the beginning of fi le
The position of the fi le object is at 10
rs = [1, 2, 3, 4, 5, 6]
>>>
The source PDF displays some characters in this program as β€œfi le” because of the textbook text extraction. The logical program structure, methods and statements are preserved here as represented in the uploaded source.
verakworld.com

2.7 Creating and Traversing a Text File

After learning how to open and close a file, read and write data, find the position of the file object and move it to a desired location, basic operations can be performed on a text file.

The chapter uses practice.txt for these operations.

2.7.1 Creating a File and Writing Data

To create a text file, use the open() method with a filename and mode.

If a file with the same name already exists, the behaviour depends on the mode:

  • In write mode (w), existing contents are lost and an empty file is created with the same name.
  • In append mode (a), new data is written after the existing data.
  • If the file does not exist, a new empty file is created in both cases.

Program 2-3 β€” To Create a Text File and Write Data in It

# program to create a text file and add data
fileobject=open("practice.txt","w+")
while True:
    data= input("Enter data to save in the text file: ")
    fileobject.write(data)
    ans=input("Do you wish to enter more data?(y/n): ")
    if ans=='n': break
fileobject.close()

Output of Program 2-3

>>>
RESTART: Path_to_file\Program2-3.py
Enter data to save in the text file: I am interested to learn about
Computer Science
Do you wish to enter more data?(y/n): y
Enter data to save in the text file: Python is easy to learn
Do you wish to enter more data?(y/n): n
>>>

2.7.2 Traversing a File and Displaying Data

To read and display data stored in a text file, the file is opened in read mode and reading begins from the beginning.

Program 2-4 β€” To Display Data from a Text File

fileobject=open("practice.txt","r")
str = fileobject.readline()
while str: 
    print(str)
    str=fileobject.readline()
fileobject.close()

In this program, readline() is used inside a while loop to read data line by line. The lines are displayed using print(). When the end of the file is reached, readline() returns an empty string. Finally, the file is closed.

Output of Program 2-4

>>>
I am interested to learn about Computer SciencePython is easy to learn
verakworld.com

Program 2-5 β€” Reading and Writing Operation in a Text File

A single program can perform both reading and writing using a single file object. Since both operations are performed using the same file object, the file is opened in w+ mode.

fileobject=open("report.txt", "w+")
print ("WRITING DATA IN THE FILE")
print() # to display a blank line
while True:
    line= input("Enter a sentence ")
    fileobject.write(line)
    fileobject.write('\n')
    choice=input("Do you wish to enter more data? (y/n): ")
    if choice in ('n','N'): break
print("The byte position of file object is ",fileobject.tell())
fileobject.seek(0) #places file object at beginning of file
print()
print("READING DATA FROM THE FILE")
str=fileobject.read()
print(str)
fileobject.close()

Output of Program 2-5

>>>
RESTART: Path_to_file\Program2-5.py
WRITING DATA IN THE FILE
Enter a sentence I am a student of class XII
Do you wish to enter more data? (y/n): y
Enter a sentence my school contact number is 4390xxx8
Do you wish to enter more data? (y/n): n
The byte position of file object is 67
READING DATA FROM THE FILE
I am a student of class XII
my school contact number is 4390xxx8
>>>
Exam Point: The program uses w+ for both writing and reading, tell() to find the current byte position and seek(0) to move the file object to the beginning.
verakworld.com

2.8 The Pickle Module

Python considers everything as an object. Therefore, data types such as lists, tuples and dictionaries are also objects.

During program execution, it may be necessary to store the current state of variables so that it can be retrieved later. The chapter gives the example of a video game where the current level/stage and score may need to be stored.

Python provides a module called Pickle to save an object structure along with its data.

Pickle Module: The Pickle module is used for serializing and de-serializing a Python object structure.

Serialization / Pickling

Serialization is the process of transforming data or an object in memory (RAM) into a stream of bytes called byte streams. These byte streams can be stored in a binary file on a disk or database or sent through a network.

The serialization process is also called pickling.

De-serialization / Unpickling

De-serialization or unpickling is the inverse of pickling, where a byte stream is converted back to a Python object.

Important Points

  • The pickle module deals with binary files.
  • Data are not written but dumped.
  • Data are not read but loaded.
  • The pickle module must be imported to load and dump data.
  • The module provides dump() and load() methods.
  • dump() is used for pickling.
  • load() is used for unpickling.
Python Object
in RAM
β†’
Serialization
(Pickling)
β†’
Byte Stream
β†’
Binary File
Binary File
β†’
Byte Stream
β†’
De-serialization
(Unpickling)
β†’
Python Object
verakworld.com

2.8.1 The dump() Method

The dump() method converts Python objects into a form suitable for writing to a binary file. The file must be opened in binary write mode (wb).

Syntax
dump(data_object, file_object)

Here, data_object is the object to be dumped to the file using the file handle named file_object.

Program 2-6 β€” Pickling Data in Python

import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("mybinary.dat", "wb")
pickle.dump(listvalues,fileobject)
fileobject.close()

2.8.2 The load() Method

The load() method loads data from a binary file. The file is opened in binary read mode (rb).

Syntax
Store_object = load(file_object)

The pickled Python object is loaded from the file having the file handle file_object and stored in a new object called Store_object.

Program 2-7 β€” Unpickling Data in Python

import pickle
print("The data that were stored in file are: ")
fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)

Output of Program 2-7

>>>
RESTART: Path_to_file\Program2-7.py
The data that were stored in file are:
[1, 'Geetika', 'F', 26]
>>>
verakworld.com

2.8.3 File Handling Using Pickle Module

Just as data can be written to and displayed from a text file, data can also be added to and displayed from a binary file.

Program 2-8 accepts an employee record from the user and appends it to a binary file named empfile.dat. The records are then read from the binary file and displayed.

Program 2-8 β€” Basic Operations on a Binary File Using Pickle

# Program to write and read employee records in a binary file
import pickle
print("WORKING WITH BINARY FILES")
bfile=open("empfile.dat","ab")
recno=1
print ("Enter Records of Employees")
print()
#taking data from user and dumping in the file as list object
while True:
    print("RECORD No.", recno)
    eno=int(input("\tEmployee number : "))
    ename=input("\tEmployee Name : ")
    ebasic=int(input("\tBasic Salary : "))
    allow=int(input("\tAllowances : "))
    totsal=ebasic+allow
    print("\tTOTAL SALARY : ", totsal)
    edata=[eno,ename,ebasic,allow,totsal]
    pickle.dump(edata,bfile)
    ans=input("Do you wish to enter more records (y/n)? ")
    recno=recno+1
    if ans.lower()=='n':
        print("Record entry OVER ")
        print()
        break
# retrieving the size of file
print("Size of binary file (in bytes):",bfile.tell())
bfile.close()
# Reading the employee records from the file using load() module
print("Now reading the employee records from the file")
print()
readrec=1
try:
    with open("empfile.dat","rb") as bfile:
        while True:
            edata=pickle.load(bfile)
            print("Record Number : ",readrec)
            print(edata)
            readrec=readrec+1
except EOFError:
    pass
bfile.close()

Output of Program 2-8

>>>
RESTART: Path_to_file\Program2-8.py
WORKING WITH BINARY FILES
Enter Records of Employees
RECORD No. 1
Employee number : 11
Employee Name : D N Ravi
Basic Salary : 32600
Allowances : 4400
TOTAL SALARY : 37000
Do you wish to enter more records (y/n)? y
RECORD No. 2
Employee number : 12
Employee Name : Farida Ahmed
Basic Salary : 38250
Allowances : 5300
TOTAL SALARY : 43550
Do you wish to enter more records (y/n)? n
Record entry OVER
Size of binary file (in bytes): 216
Now reading the employee records from the file
Record Number : 1
[11, 'D N Ravi', 32600, 4400, 37000]
Record Number : 2
[12, 'Farida Ahmed', 38250, 5300, 43550]
>>>

Each employee record is stored as a list in empfile.dat. Therefore, while reading the file, a list representing each employee record is displayed.

The program also uses a try..except block to handle the end-of-file exception.

Exam Point: Remember the relationship: pickle.dump() β†’ storing/pickling an object in a binary file, and pickle.load() β†’ retrieving/unpickling an object from a binary file.
verakworld.com

⚑ Quick Revision

Important Definitions

  • File: A named location on a secondary storage media where data are permanently stored for later access.
  • Serialization: Transforming data or an object in memory into a stream of bytes.
  • Pickling: The serialization process.
  • Unpickling: The process of converting a byte stream back to a Python object.

Important Terms

Text File
Contains human-readable characters.
Binary File
Stores data as a stream of bytes.
File Handle
File object returned by open().
EOL
End of Line character.
EOF
End of File.
Pickle
Module for serializing and de-serializing Python objects.

Important Methods

Method Purpose
open()Opens a file and returns a file object.
close()Closes a file.
write()Writes a single string.
writelines()Writes multiple strings.
read()Reads specified bytes or the entire file.
readline()Reads a line from a file.
readlines()Reads all lines as a list of strings.
tell()Returns current file-object position.
seek()Moves file object to a particular position.
dump()Pickles/writes a Python object to a binary file.
load()Unpickles/loads a Python object from a binary file.

Important Syntax

file_object = open(file_name, access_mode)

file_object.close()

with open(file_name, access_mode) as file_object:

file_object.read(n)

file_object.tell()

file_object.seek(offset [, reference_point])

dump(data_object, file_object)

Store_object = load(file_object)

Important File Modes

Mode Purpose Position
rRead-onlyBeginning
rbBinary read-onlyBeginning
r+Read and writeBeginning
wWrite; existing contents overwrittenBeginning
wb+Binary read/write; existing contents overwrittenBeginning
aAppendEnd
a+Append and readEnd

Important Differences

Basis Text File Binary File
Content Human-readable characters Non-human-readable data
Representation Bytes representing character values Bytes representing actual content
Examples .txt, .py, .csv Images, audio, video, compressed and executable files
Access Can be opened using a text editor Requires specific software
Method Difference
readline() Reads one complete line, or specified bytes up to newline.
readlines() Reads all lines and returns them as a list of strings.
write() Writes a single string and returns number of characters written.
writelines() Writes multiple strings and does not return the number of characters written.

Important Programs to Revise

  • Program 2-1 β€” Writing and reading to a text file
  • Program 2-2 β€” Application of seek() and tell()
  • Program 2-3 β€” Creating a text file and writing data
  • Program 2-4 β€” Displaying data from a text file
  • Program 2-5 β€” Reading and writing operation in a text file
  • Program 2-6 β€” Pickling data in Python
  • Program 2-7 β€” Unpickling data in Python
  • Program 2-8 β€” Basic operations on a binary file using pickle module

Important Diagrams / Structures

  • Text file and binary file classification
  • File opening modes and their offset positions
  • File-object movement using seek() and tell()
  • Serialization and de-serialization using the Pickle module
verakworld.com

πŸ“ Important Questions

1-Mark Questions

1. What is a file?
2. Name the two main types of data files.
3. What is the default EOL character in Python?
4. Which function is used to open a file in Python?
5. Which method is used to close a file?
6. Which method returns the current position of a file object?
7. Which method is used to position a file object at a particular position?
8. Which module is used for pickling Python objects?
9. Which method is used for pickling?
10. Which method is used for unpickling?

2-Mark Questions

1. Differentiate between a text file and a binary file.
2. What is the purpose of the open() function? Write its syntax.
3. What is the use of the close() method?
4. Explain the advantage of opening a file using the with clause.
5. Differentiate between write() and writelines().
6. Differentiate between readline() and readlines().
7. What are tell() and seek() methods used for?
8. Define pickling and unpickling.

3-Mark Questions

1. Explain the different file open modes given in the chapter.
2. Explain the read(), readline() and readlines() methods.
3. Explain serialization and de-serialization of a Python object.
4. Explain the working of seek() with its reference points.

4/5-Mark Questions

1. Write and explain a Python program to write and read data from a text file.
2. Write and explain a Python program demonstrating seek() and tell().
3. Explain the Pickle module and its dump() and load() methods with suitable programs.
4. Explain the basic operations on a binary file using the Pickle module.
5. Write a program to store employee records in a binary file and read the records using the Pickle module.
verakworld.com

πŸ“˜ Textbook Exercise-Based Important Questions

The following questions are included in the uploaded chapter’s exercise and should be revised carefully.

  1. Differentiate between:
    1. text file and binary file
    2. readline() and readlines()
    3. write() and writelines()
  2. Write the use and syntax for:
    1. open()
    2. read()
    3. seek()
    4. dump()
  3. Write the file mode and Python statements for:
    1. a text file β€œexample.txt” in both read and write mode
    2. a binary file β€œbfile.dat” in write mode
    3. a text file β€œtry.txt” in append and read mode
    4. a binary file β€œbtry.dat” in read only mode
  4. Why is it advised to close a file after completing read and write operations? What happens if it is not closed? Will some error message be flashed?
  5. What is the difference between:
    P = open("practice.txt","r")
    P.read(10)
    and
    with open("practice.txt", "r") as P:
        x = P.read()
  6. Write commands to write the following lines to hello.txt when the file is opened in append mode:
    • β€œ Welcome my class”
    • β€œIt is a fun place”
    • β€œYou will learn and play”
  7. Write a Python program to open hello.txt in read mode and display its contents. What difference occurs if the file is opened in write mode instead of append mode?
  8. Write a program to accept strings/sentences until the user enters β€œEND”, save the data in a text file and display only those sentences beginning with an uppercase alphabet.
  9. Define pickling. Explain serialization and deserialization of a Python object.
  10. Write a program to enter records containing Item No, Item_Name, Qty and Price in a binary file, accept the number of records from the user, read the file and display Item No, Item Name, Quantity, Price per item and Amount calculated as Price Γ— Qty.
verakworld.com

🎯 Final Revision Checklist

Files

Know the definition and purpose of storing data permanently.

File Types

Revise text files and binary files with their differences.

Opening

Revise open(), file object and access modes.

Writing

Revise write() and writelines().

Reading

Revise read(), readline() and readlines().

Offsets

Revise tell(), seek() and reference points.

Text Files

Revise creation, writing, traversing and displaying data.

Pickle

Revise serialization, unpickling, dump() and load().

Board Exam Revision Tip: Give special attention to definitions, differences, file modes, method syntax, seek()/tell(), text-file programs and Pickle-module programs because these are directly represented in the chapter’s concepts, examples and exercise.
verakworld.com

πŸ“Œ Chapter Summary

  • A file is a named location on secondary storage where data are permanently stored for later access.
  • Text files contain textual information consisting of alphabets, numbers and special symbols.
  • Text files use extensions such as .txt, .py, .c, .csv and .html.
  • Each line of a text file is terminated by an End of Line character.
  • Binary files consist of data stored as a stream of bytes.
  • open() opens a file and returns a file object/file handle.
  • close() closes the file and releases resources.
  • write() writes a string to a text file.
  • writelines() writes multiple strings.
  • read() reads a specified number of bytes or the entire file.
  • readline() reads a line from a file.
  • readlines() reads all lines and returns them as a list.
  • tell() gives the current position of the file object.
  • seek() positions the file object at a particular location.
  • Pickling converts a Python object into a byte stream.
  • dump() is used to write objects to a binary file.
  • load() is used to read objects from a binary file.
verakworld.com

2nd PUC Computer Science β€” Chapter 2: File Handling in Python

Complete Short Notes & Exam Preparation Guide

Based on the NCERT Class XII Computer Science textbook chapter.

verakworld.com

πŸ“ This article was researched and written by Venkatesh A, Founder of verakworld.com.

Leave a Comment