PUC II STATE BOARD / CBSE XII COMPUTER SCIENCE - Chapter 2 File Handling in Python, collection of questions

 


PUC II STATE BOARD / CBSE XII COMPUTER SCIENCE - Chapter 2 File Handling in Python, collection of questions 

Basics of File Handling

1.    What is a file in Python?
A) A temporary storage in RAM
B) A named location on secondary storage to store data permanently
✅
C) A program variable
D) None of these

2.    Which of the following is a text file?
A) .txt
✅
B) .exe
C) .mp4
D) .bin

3.    Which of the following is a binary file?
A) .txt
B) .py
C) .dat
✅
D) .csv

4.    Text files store data as:
A) Images
B) Audio
C) Characters in ASCII or Unicode
✅
D) Executable code

5.    Which of the following is true about binary files?
A) Human readable
B) Cannot be read by any program
C) Requires specific software to read/write
✅
D) None of the above


Opening and Closing Files

6.    Which Python function is used to open a file?
A) fopen()
B) file()
C) open()
✅
D) create()

7.    What is the default mode in the open() function?
A) Write
B) Read
✅
C) Append
D) Binary

8.    What does file_object.closed return?
A) File content
B) Name of file
C) True if file is closed, else False
✅
D) None of these

9.    Which mode is used to open a file for reading only?
A) 'w'
B) 'r'
✅
C) 'a'
D) 'rb'

10.                       Which mode opens a file for both reading and writing from the start?
A) 'r+'
✅
B) 'w'
C) 'a'
D) 'rb'

11.                       What is the advantage of using with open() over open()?
A) File is automatically closed
✅
B) File size is reduced
C) File can be opened faster
D) File becomes text only

12.                       What happens if a file is not closed explicitly?
A) Data is lost if not flushed
✅
B) File is deleted
C) File converts to binary
D) Nothing happens


Writing to a File

13.                       Which method writes a single string to a file?
A) writelines()
B) write()
✅
C) dump()
D) append()

14.                       writelines() method takes what as input?
A) Single string
B) Iterable object like list/tuple
✅
C) Binary data
D) None

15.                       What happens if we open an existing file in write mode?
A) File contents are preserved
B) File contents are erased
✅
C) File is copied
D) None

16.                       To write numeric data to a file, it must first be converted to:
A) float
B) list
C) string
✅
D) int

17.                       write() method returns:
A) Number of lines written
B) Number of characters written
✅
C) None
D) File size


Reading from a File

18.                       Which method reads the entire file as a string?
A) readlines()
B) readline()
C) read()
✅
D) writelines()

19.                       read(n) reads:
A) n lines
B) n characters
✅
C) entire file
D) n bytes only in binary

20.                       readline() reads:
A) One line at a time
✅
B) Entire file
C) Entire list
D) n lines

21.                       readlines() returns:
A) String
B) List of lines
✅
C) Dictionary
D) Single line

22.                       Which method splits each line into words?
A) splitlines()
B) split()
✅
C) write()
D) dump()

23.                       splitlines() differs from split() because it:
A) Splits file into bytes
B) Returns list of lines instead of words
✅
C) Writes to file
D) Reads binary files


File Positioning

24.                       Which method returns current file position?
A) seek()
B) tell()
✅
C) read()
D) close()

25.                       seek(offset, 0) positions file at:
A) End
B) Current position
C) Offset bytes from start
✅
D) Offset bytes from end

26.                       seek(offset, 2) moves file pointer:
A) From beginning
B) From current
C) From end
✅
D) None

27.                       Why is file offset useful?
A) To append data only
B) To access data randomly
✅
C) To close file
D) To compress file


Pickle Module

28.                       What is pickling in Python?
A) Converting Python object to bytes
✅
B) Converting string to int
C) Writing to text file
D) Closing file

29.                       What is unpickling?
A) Reading string
B) Converting bytes back to Python object
✅
C) Writing numbers
D) Opening text file

30.                       Which mode is used to write pickled object?
A) 'w'
B) 'wb'
✅
C) 'r'
D) 'rb'

31.                       Which mode is used to read pickled object?
A) 'r'
B) 'rb'
✅
C) 'w'
D) 'wb'

32.                       Method used to save Python object in a binary file:
A) write()
B) dump()
✅
C) read()
D) readlines()

33.                       Method used to load Python object from a binary file:
A) write()
B) load()
✅
C) read()
D) readline()

34.                       Pickle module deals with:
A) Text files
B) Binary files
✅
C) JSON files
D) CSV files


File Modes

35.                       Mode to open text file for appending:
A) 'w'
B) 'a'
✅
C) 'r'
D) 'rb'

36.                       Mode to read and append:
A) 'r+'
B) 'a+'
✅
C) 'w+'
D) 'rb+'

37.                       Binary write and read mode:
A) 'wb'
B) 'wb+'
✅
C) 'rb'
D) 'ab'

38.                       Opening a non-existing file in 'r' mode will:
A) Create the file
B) Raise error
✅
C) Append data
D) Open empty file

39.                       w+ mode:
A) Reads only
B) Writes only
C) Reads and writes, overwriting existing content
✅
D) Appends only


Looping & Traversing Files

40.                       To read a file line by line, use:
A) for loop
✅
B) while loop only
C) readlines() only
D) write()

41.                       EOFError occurs in pickle when:
A) File not found
B) End of file is reached
✅
C) File is closed
D) File is empty

42.                       with open(file) as f: automatically:
A) Reads only
B) Writes only
C) Closes file after block
✅
D) Appends data

43.                       File pointer in append mode is:
A) Beginning
✅
B) End
✅
C) Middle
D) Random


Programs & Examples

44.                       In file_object.write(str(marks)), what is marks?
A) String
B) Converted integer to string
✅
C) List
D) File object

45.                       Which function flushes buffer to file when closing?
A) write()
B) close()
✅
C) tell()
D) seek()

46.                       What does file_object.writelines(lines) return?
A) Number of lines
B) None
✅
C) List of characters
D) File size

47.                       In pickle, multiple records are stored as:
A) Strings
B) Lists
✅
C) Integers
D) Bytes only

48.                       To read all lines as a list from a file:
A) read()
B) readline()
C) readlines()
✅
D) write()

49.                       Which module is needed to serialize Python objects?
A) io
B) pickle
✅
C) os
D) sys

50.                       seek(10) positions file pointer at:
A) Beginning
B) 10 bytes from start
✅
C) 10 lines from start
D) End


50 MCQ Questions with Answers (1 mark each)

1.    A file in Python is a named location on secondary storage where data are stored permanently. ✅

2.    Text files store human-readable characters. ✅

3.    Binary files store data as bytes not readable by humans. ✅

4.    Which Python function is used to open a file? open() ✅

5.    Default mode for open() function is read mode ('r'). ✅

6.    Which method closes a file in Python? close() ✅

7.    Which mode opens a file for writing and overwrites existing content? 'w' ✅

8.    Which mode appends data to the end of a file? 'a' ✅

9.    The write() method writes a single string to a file. ✅

10.                       writelines() method writes multiple strings. ✅

11.                       Which method reads the entire file content? read() ✅

12.                       Which method reads one line at a time? readline() ✅

13.                       Which method reads all lines into a list? readlines() ✅

14.                       What does tell() return? current file object position in bytes ✅

15.                       What does seek() do? moves file object to a specific byte position ✅

16.                       Using with open() automatically closes the file ✅

17.                       Text files usually end each line with newline character (\n) ✅

18.                       ASCII value 65 corresponds to the character ‘A’ ✅

19.                       Binary files require specific software to access. ✅

20.                       Pickle module is used for serializing Python objects. ✅

21.                       Serialization in Python is also called pickling. ✅

22.                       Deserialization in Python is called unpickling. ✅

23.                       Pickle’s dump() writes data to a binary file ✅

24.                       Pickle’s load() reads data from a binary file ✅

25.                       If a file object is reassigned, the previous file is automatically closed ✅

26.                       read(n) reads n bytes from a file. ✅

27.                       readline(n) reads up to n bytes or a full line ✅

28.                       readlines() returns a list of lines ✅

29.                       Text file extensions include .txt, .py, .csv ✅

30.                       Binary files may include images, audio, video ✅

31.                       Using write() method, numbers must be converted to string ✅

32.                       File opened in 'rb' mode can read binary data ✅

33.                       File opened in 'wb' mode can write binary data ✅

34.                       File opened in 'r+' mode can read and write ✅

35.                       File opened in 'a+' mode can append and read ✅

36.                       split() returns words in a line as list ✅

37.                       splitlines() returns lines as list elements ✅

38.                       Using seek(0) moves the file object to the beginning ✅

39.                       Using seek(offset, 2) moves file object from end of file ✅

40.                       File offset is counted in bytes ✅

41.                       If a file opened in 'w' mode already exists, its content is overwritten ✅

42.                       file.closed returns True if file is closed ✅

43.                       Python's io module contains file handling functions ✅

44.                       file.name returns the name of the file ✅

45.                       Pickling stores Python objects as byte streams ✅

46.                       Binary files are sensitive to even a single-bit change ✅

47.                       End-of-file (EOF) is reached when read returns empty string ✅

48.                       file.mode returns mode in which file was opened ✅

49.                       w+ mode allows writing and reading ✅

50.                       rb+ mode allows reading and writing in binary ✅


1-Mark Questions (10 questions with answers)

1.    What is a file in Python?
Answer: A named location on secondary storage where data are stored permanently.

2.    Name two types of files.
Answer: Text file and Binary file.

3.    Which method is used to close a file?
Answer:
close()

4.    What character usually marks the end of a line in a text file?
Answer: Newline character
\n

5.    Which method reads one complete line from a file?
Answer:
readline()

6.    Which method reads all lines as a list?
Answer:
readlines()

7.    Which function opens a file in Python?
Answer:
open()

8.    What mode is used to append data to an existing file?
Answer:
'a'

9.    Pickle module is used to ________ Python objects.
Answer: Serialize (pickling) and deserialize (unpickling)

10.                       What does tell() return?
Answer: Current position of the file object in bytes


2-Mark Questions (10 questions with answers)

1.    Differentiate text file and binary file.
Answer: Text files contain human-readable characters and can be opened with text editors. Binary files contain bytes representing images, audio, or executable content, not human-readable.

2.    Write syntax of open() function.
Answer:
file_object = open(file_name, access_mode)

3.    Difference between read() and readline().
Answer:
read() reads a specified number of bytes or entire file, readline() reads a single line from the file.

4.    Difference between write() and writelines().
Answer:
write() writes a single string; writelines() writes multiple strings from a list or iterable.

5.    What is the purpose of seek()?
Answer: Moves the file object to a specific byte position in a file.

6.    What is serialization and deserialization in Python?
Answer: Serialization (pickling) converts a Python object to a byte stream; deserialization (unpickling) converts byte stream back to Python object.

7.    How do you automatically close a file after opening it?
Answer: Using
with open(file_name, mode) as file_object:

8.    Name one difference between 'w+' and 'a+' mode.
Answer:
'w+' overwrites existing content; 'a+' appends at the end.

9.    What is returned by file.closed and file.mode?
Answer:
file.closed returns True if file is closed; file.mode returns the access mode.

10.                       Which Python module is used to handle files?
Answer:
io module


3-Mark Questions (10 questions with answers)

1.    Explain the difference between split() and splitlines().
Answer:
split() splits a line into words and returns a list; splitlines() splits the file into lines and returns a list of lines.

2.    Write the Python statement to open a text file example.txt in read and write mode.
Answer:
file_object = open("example.txt", "r+")

3.    How do you write multiple lines to a file using Python?
Answer: Use
writelines(list_of_strings) after opening file in write or append mode.

4.    Explain the difference between opening a file using open() and with open().
Answer:
with open() automatically closes the file after the block is executed, even if an exception occurs; open() requires manual close().

5.    How can you read a file line by line in Python?
Answer: Using a loop with
readline(), for example:

file = open("file.txt", "r")

line = file.readline()

while line:

    print(line)

    line = file.readline()

file.close()

6.    What happens if you try to read a binary file in text mode?
Answer: You may get garbage values or unreadable content, as binary files are not human-readable.

7.    Explain 'rb+' mode in Python file handling.
Answer:
'rb+' opens the file for reading and writing in binary mode from the beginning of the file.

8.    How is the current position of file object obtained in Python?
Answer: Using
tell() method.

9.    Write Python code to write a string Hello World to a file sample.txt.
Answer:

file = open("sample.txt", "w")

file.write("Hello World\n")

file.close()

10.                       What is the difference between 'r+' and 'w+' modes?
Answer:
'r+' reads and writes without deleting content; 'w+' overwrites the existing content.


5-Mark Questions (10 questions with elaborated answers)

1.    Explain pickling and unpickling in Python with an example.
Answer:
Pickling is the process of converting a Python object into a byte stream for storage in a binary file. Unpickling is converting the byte stream back to Python object.
Example:

import pickle

data = [1, "Alice", 25]

# Pickling

with open("data.dat", "wb") as file:

    pickle.dump(data, file)

# Unpickling

with open("data.dat", "rb") as file:

    obj = pickle.load(file)

print(obj)  # Output: [1, 'Alice', 25]

2.    Write a program to accept strings from the user till 'END' is entered, save in a file and display sentences starting with uppercase.
Answer:

f = open("data.txt", "w")

while True:

    s = input("Enter string: ")

    if s == "END":

        break

    f.write(s + "\n")

f.close()

 

f = open("data.txt", "r")

for line in f:

    if line[0].isupper():

        print(line.strip())

f.close()

3.    Explain the difference between text file and binary file.
Answer:

  • Text file: Human-readable, stores characters as bytes using ASCII/Unicode. Examples: .txt, .csv. Can be opened with text editors.
  • Binary file: Stores bytes as-is for images, audio, video, or pickled objects. Not human-readable. Requires specific software to access.

4.    Write Python statements to open files in given modes:
Answer:
a)
example.txt in read/write mode: open("example.txt", "r+")
b)
bfile.dat in write mode: open("bfile.dat", "wb")
c)
try.txt in append/read mode: open("try.txt", "a+")
d)
btry.dat in read-only mode: open("btry.dat", "rb")

5.    Text Box: Habbit2CodeExplain the use of seek() and tell() with example.
Answer:

  • tell() returns current byte position of the file object.
  • seek(offset, reference) moves file pointer to a specified byte offset.
    Example:

f = open("data.txt", "r")

print(f.tell())  # Current position

f.seek(5)        # Move to 5th byte

print(f.read(10))

f.close()

6.    Explain differences between read(), readline(), and readlines().
Answer:

  • read(n): Reads n bytes or entire file if n is negative.
  • readline(n): Reads one line, optionally up to n bytes.
  • readlines(): Reads all lines and returns a list of strings, each ending with \n.

7.    Explain file modes 'r', 'w', 'a', 'r+', 'w+', 'a+' with examples.
Answer:

  • 'r': Read-only.
  • 'w': Write-only, overwrites existing content.
  • 'a': Append at end.
  • 'r+': Read and write.
  • 'w+': Write and read, overwrites existing content.
  • 'a+': Append and read.
    Example:

Text Box: Habbit2Codef = open("file.txt", "a+")

f.write("New line\n")

f.seek(0)

print(f.read())

f.close()

8.    Write a program to store employee records in binary using Pickle and read them.
Answer:

import pickle

bfile = open("emp.dat", "ab")

rec = [101, "Alice", 30000]

pickle.dump(rec, bfile)

bfile.close()

 

with open("emp.dat", "rb") as bfile:

    emp = pickle.load(bfile)

    print(emp)

9.    Explain difference between write() and writelines() with example.
Answer:

  • write(): Writes single string. Returns number of characters written.
  • writelines(): Writes multiple strings from iterable, does not return number of characters.
    Example:

f = open("file.txt", "w")

f.write("Hello\n")

lines = ["Line1\n", "Line2\n"]

f.writelines(lines)

f.close()

10.                       Text Box: Habbit2CodeExplain how to perform reading and writing in a single file object.
Answer:
Open file in
'w+' or 'a+' mode. Write data using write(), then use seek(0) to move pointer to start for reading.
Example:

f = open("report.txt", "w+")

f.write("Hello\n")

f.seek(0)

print(f.read())

f.close()


 [KINDLY NOTE: CROSS CHECK ALL ANSWERS BEFORE USE WITH YOUR TEXT BOOK/LECTURER/ACCURACY OF ANSWERS MAY NOT BE 100% CORRECT AS THEY ARE EXTRACTED FROM AI TOOLS, QUANTITY OF ANSWER MAY NOT BE SUFFICIENT FOR SOME QUESTIONS, THIS COLLECTION IS JUST FOR REFERENCE ]

 

Comments