Computer Science · Class 12 Optional
Ch 2File Handling in Python — Class 12 Computer Science, concept-first.
A program’s variables exist only while the program runs. Once execution ends, the data stored in those variables is lost. This means every time you run the program, you must re-enter the input, and any output produced during the previous run is gone.
22
Q&A
8
Concepts
40m
Section weightage
Computational Thinking and Programming – 2 · across all 7 lessons
Key concepts
Hover a concept to preview it and jump to its most relevant Q&A.
File Size Comparison
Think about the last time you tried to email a document or upload a photo to a website. If the file was too large, the website probably stopped you or the email refused to send.
Most relevant Q&A
Chapter contents
The NCERT structure, section by section. Open a section to see its questions, then read the concept-first solution.
Introduction to Files
A program’s variables exist only while the program runs. Once execution ends, the data stored in those variables is lost.
Types of Files
Every file on a computer — whether it is a text document, an image, a video, or a program — is stored as a collection of 0s and 1s. That is the only language a computer understands.
Text file
A text file is simply a sequence of characters — alphabets, digits, and special symbols — stored permanently on a disk. Common examples include files with extensions like .txt, .py, and .csv.
Binary Files
Binary files store data as a sequence of bytes (0s and 1s), just like text files. The critical difference is what those bytes represent.
Opening and Closing a Text File
In real-world applications, programs work with data arriving from many different sources — databases, CSV files, HTML, XML, JSON feeds, and more.
Opening a file
To work with a file in Python, the first step is to open it. You do this using the open() function, which returns a file object (also called a file handle).
Closing a file
Once a file has been opened and you have finished reading from it or writing to it, you must close it.
Opening a file using with clause
The with clause in Python provides a cleaner and safer way to work with files. Its real power is that it handles file closing automatically — you never have to remember to call close().
Writing to a Text File
To write data into a file, you must first open it in either write mode ('w') or append mode ('a'). If you open an existing file in write mode, its previous contents are erased and the file object is p…
+−Think & Reflect1 question
The write() method
The write() method is how you actually put data into a text file. It does not create a file — that is the job of the open() function with the 'w' mode.
The writelines() method
2 QThe writelines() method is designed for writing multiple strings to a file in one go. Instead of calling write() repeatedly for each string, you pass an iterable object — like a list or a tuple — that…
+−Activities1 question
Reading from a Text File
Before you can read from a file, you must make sure it is opened in a mode that permits reading — "r", "r+", "w+", or "a+".
The read() method
The read() method is how you pull data out of a file and into your Python program. It reads a specified number of bytes (characters) from the file, starting from the current position of the file point…
The readline([n]) method
The readline() method reads exactly one line from a file. A "line" in a text file is any sequence of characters that ends with a newline character (n).
The readlines() method
The readlines() method reads all the lines of a file at once and returns them as a list of strings. Each string in the list corresponds to one line from the file, and crucially, each string includes t…
Setting Offsets in a File
The functions you have learnt so far — read(), readline(), readlines(), write(), writelines() — all access data sequentially: the file pointer moves forward as you read or write, and you cannot easily…
The tell() method
The tell() method answers a simple question: "Where exactly am I in this file right now?" When you read from or write to a file, the file object keeps track of its current position — like a cursor tha…
The seek() method
The seek() method lets you move the file object to a specific byte position inside a file. This is essential when you need to read from or write to a particular location without going through the enti…
+−Think & Reflect1 question
Creating and Traversing a Text File
Having learnt how to open and close a file, read and write data in a text file, and find or move the file object's position, let's now put these skills together to perform two basic operations on a te…
Creating a file and writing data
To create a file in Python, you use the open() method. This method takes two essential arguments: the filename and the mode in which you want to open it.
Traversing a file and displaying data
To read data back from a text file, you must open it in read mode ("r"). Once opened, reading begins from the very first byte of the file — the file pointer is at position 0.
The Pickle Module
Python treats everything as an object — lists, tuples, dictionaries, and even custom data structures are all objects.
The dump() method
The dump() method is how you write Python objects into a binary file — a process called pickling. Pickling converts a Python object (like a list, dictionary, or number) into a byte stream that can be…
The load() method
The load() method is the counterpart of dump() — it brings data back from a binary file into a Python object. This process is called unpickling.
File handling using pickle module
When you write data to a text file, everything becomes a string. Numbers, lists, dictionaries — all get converted to text.
Summary
- A file is a named location on a secondary storage media where data are permanently stored for later access.
Exercises
+−Show 10 questionsHide questions10 questions
- Q1Differentiate between: a) text file and binary file b) readline() and readlines() c) write() and writelines()Free
- Q2Write the use and syntax for the following methods: a) open() b) read() c) seek() d) dump()Free
- Q3Write the file mode that will be used for opening the following files. Also, write the Python statements to open the following files: a) a t…Free
- Q4Why is it advised to close a file after we are done with the read and write operations? What will happen if we do not close it? Will some er…Preview
- Q5What is the difference between the following set of statements (a) and (b): a) ```python P = open("practice.txt","r") P.read(10) ``` b) ```p…Preview
- Q6Write a command(s) to write the following lines to the text file named hello.txt. Assume that the file is opened in append mode. "Welcome my…Preview
- Q7Write a Python program to open the file hello.txt used in question no 6 in read mode to display its contents. What will be the difference if…Preview
- Q8Write a program to accept string/sentences from the user till the user enters "END". Save the data in a text file and then display only thos…Preview
- Q9Define pickling in Python. Explain serialization and deserialization of Python object.Preview
- Q10Write a program to enter the following records in a binary file: | Field | Type | | --- | --- | | Item No | integer | | Item_Name | string |…Preview
CBSE Sample Papers
Questions from official CBSE sample papers.
+−Show 5 questionsHide questions5 questions
- Q1A csv file "P_record.csv" contains the records of patients in a hospital. Each record of the file contains the following data : - Name of a…Preview
- Q2(a) Write a Python function that counts and returns the number of digits appearing in the text file "Space.txt". For example, if the file co…Preview
- Q3Q. 17 and 18 are ASSERTION (A) and REASONING (R) based questions. Mark the correct choice as (A) Both (A) and (R) are true and (R) is the co…Preview
- Q4Sangeeta is a Python programmer working in a computer hardware company. She has to maintain the records of the peripheral devices. She creat…Preview
- Q5The syntax of seek() is: file_object.seek(offset[,reference_point]) What is the default value of reference_point? (a) 0 (b) 1 (c) 2 (d) 3Preview