Worksheets › Class 12 › File Handling in Python
Class 12 · Computer Science worksheetFile Handling in Python
CBSE Computer Science. Text files: modes, read, readline, readlines, write, seek and tell; binary files with pickle; CSV files with reader and writer. Every sheet has 20 questions in three sections and an answer key, and the questions change every time.
Sample questions
Real questions from this chapter, as the app sets them. Tap Answer to see the answer and working.
Section A · multiple choice
- 1.
Which file mode opens a file for writing and erases what it held?
- 'r'
- 'r+'
- 'a'
- 'w'
Answer
(d) 'w'
- 2.
The file notes.txt holds these lines (each ends with a newline): Old books smell nice Kites fly high in the sky The test starts at nine What does this print? f = open('notes.txt', 'r') c = 0 for line in f: if line[0] == 'T': c = c + 1 f.close() print(c)
- 1
- 2
- 3
- 0
Answer
(a) 1
count the lines starting with T
- 3.
The file notes.txt holds these lines (each ends with a newline): The river flows past our town Trees stand tall near the school Children play in the park What does this print? f = open('notes.txt', 'r') words = f.read().split() f.close() print(len(words))
- 16
- 3
- 19
- 17
Answer
(d) 17
split() breaks at spaces and newlines
Section B · short answer
- 4.
What is the difference between a text file and a binary file?
Answer
A text file holds characters that people can read, in lines ending with newline characters; a binary file holds raw bytes (such as pickled objects or images) that only programs read.
- 5.
The file notes.txt holds these lines (each ends with a newline): Bees make honey Kites fly high in the sky The bus was late today Our garden has roses Stars shine at night What does this print? f = open('notes.txt', 'r') c = 0 for line in f: if line[0] == 'S': c = c + 1 f.close() print(c)
Answer
1
count the lines starting with S
Section C · long answer
- 6.
Write a program that reads a text file and prints the number of vowels, consonants, upper-case and lower-case letters in it.
Answer
Open with open('a.txt') as f: data = f.read(); for ch in data: if ch.isalpha(): count upper or lower with isupper(); if ch.lower() in 'aeiou' add to vowels, else to consonants. Print the four counts.
Fresh sheets for your child
In the app, every File Handling in Python sheet is new: the app remembers the questions your child has already had and leaves them out. Print the sheet as a PDF, or use notebook mode and write the answers in a notebook.
Coming soon for Android and iPhone.