Kundali IQ

Home › Free notes › Class 12 Computer Science › File Handling in Python

File Handling in Python – Class 12 Computer Science notes, important questions and MCQs

NCERT Class 12 Computer Science, chapter 2. Notes, key terms, important questions with answers and MCQs.

हिंदी में पढ़ें

Chapter overview

A file is a named location on secondary storage that stores data permanently. Python works with text files, which store characters, and binary files, which store data as bytes. Files are opened with open() in a particular mode, read or written using file methods, and closed after use. The with statement closes files automatically, and the pickle module is used to store Python objects in binary files.

Opening, reading and writing text files

  • open(filename, mode) returns a file object; modes include 'r' (read, default), 'w' (write, overwrites or creates), 'a' (append), 'r+' (read and write), 'w+', 'a+', and 'b' for binary, such as 'rb' and 'wb'.
  • Writing: write(string) writes a string and returns the number of characters written; writelines(list) writes a sequence of strings; newline characters must be added explicitly.
  • Reading: read(n) reads n characters (whole file if n is omitted), readline() reads one line, readlines() returns a list of lines; with open('f.txt') as f ensures the file is closed automatically.

File pointer and binary files

  • tell() returns the current position of the file pointer in bytes; seek(offset, reference) moves it, where reference 0 is the beginning, 1 the current position and 2 the end.
  • Binary files store data in the same format as memory; the pickle module serialises (pickles) objects with pickle.dump(obj, file) and deserialises (unpickles) them with pickle.load(file).
  • Reading a pickled file until the end requires handling EOFError, for example with try and except inside a while loop.

Key terms

Text file
a file storing data as human-readable characters
Binary file
a file storing data as bytes in machine format
File mode
the purpose for which a file is opened, such as 'r', 'w' or 'a'
Pickling
converting a Python object into a byte stream to store in a file
File pointer
the marker that indicates the current position in a file

Important questions with answers

Distinguish between text files and binary files.2 marks

Text files store data as human-readable characters with each line ending in a newline character, and can be opened in a text editor. Binary files store data as bytes in the same format as memory, are not human-readable, are faster to process and are used for images, audio and pickled objects.

Explain the difference between 'w' and 'a' modes.3 marks

In 'w' mode, a new file is created if it does not exist, and if it exists, its contents are erased before writing. In 'a' mode, a new file is created if it does not exist, and if it exists, data is added at the end without erasing existing contents.

Write a program to count the number of lines, words and characters in a text file, and explain it.5 marks

The program opens the file in read mode and processes its contents. with open('story.txt', 'r') as f: lines = f.readlines(); then nl = len(lines); nw = 0; nc = 0; for line in lines: nw = nw + len(line.split()); nc = nc + len(line). Finally, print('Lines:', nl, 'Words:', nw, 'Characters:', nc). Explanation: the with statement opens story.txt and closes it automatically after the block. readlines() returns a list in which each element is one line, including its newline character, so the number of lines is the length of the list. For each line, split() breaks the line into words using whitespace, and the length of the resulting list gives the number of words in that line, which is added to the total. len(line) gives the number of characters in the line, including spaces and the newline character. If the file does not exist, open() raises FileNotFoundError, which can be handled with try and except. Other ways include reading the whole file with read() and using split() and len() on it. This program demonstrates opening files safely, reading methods and string processing.

Quick revision

  • Text and binary files.
  • open() and modes; close() and with.
  • write(), writelines(), read(), readline(), readlines().
  • tell(), seek(); pickle.dump() and pickle.load().

Exam tips

  • 'w' erases existing content; 'a' adds at the end.
  • Use with open() to avoid forgetting close().

Practice MCQs

  1. The default mode of open() is

    1. 'r'
    2. 'w'
    3. 'a'
    4. 'rb'
    Show answer

    Answer: (a) 'r'. Read mode.

  2. The module used to store Python objects in a binary file is

    1. math
    2. csv only
    3. random
    4. pickle
    Show answer

    Answer: (d) pickle. It serialises objects.

  3. The method that returns all lines of a file as a list is

    1. read()
    2. readlines()
    3. readline()
    4. write()
    Show answer

    Answer: (b) readlines(). Each line is a list element.

  4. Opening an existing file in 'w' mode

    1. appends to it
    2. raises an error
    3. erases its contents and starts fresh
    4. opens it read-only
    Show answer

    Answer: (c) erases its contents and starts fresh. Use 'a' to keep contents.

  5. The method that returns the current position of the file pointer is

    1. seek()
    2. where()
    3. pos()
    4. tell()
    Show answer

    Answer: (d) tell(). It returns bytes from the start.

  6. pickle.load() is used to

    1. write an object
    2. close a file
    3. read an object from a binary file
    4. delete a file
    Show answer

    Answer: (c) read an object from a binary file. It unpickles data.

  7. f.seek(0, 2) moves the file pointer to

    1. the beginning
    2. the second line
    3. the second byte
    4. the end of the file
    Show answer

    Answer: (d) the end of the file. Reference 2 means end.

  8. While reading a pickled file in a loop, the exception raised at the end is

    1. IOError
    2. ValueError
    3. EOFError
    4. KeyError
    Show answer

    Answer: (c) EOFError. It signals no more data.

All chapters of Class 12 Computer Science

Written by Kundali IQ from standard, well-established facts to help with revision. This is not an official NCERT publication; always read your textbook too.