Class 12 Revision Worksheet of File Handling --- Subject- Computer Science
What is the default mode in which a file is opened using open()?
A) w
B) r
C) a
D) x
Answer: B
Which method is used to read the entire content of a file as a string?
A) readline()
B) readlines()
C) read()
D) file.read_all()
Answer: C
What does the 'b' in file mode 'rb' stand for?
A) block
B) binary
C) buffer
D) bit
Answer: B
Which method is used to write data into a binary file?
A) write()
B) writelines()
C) pickle.dump()
D) csv.writer()
Answer: C
Which library is used for handling CSV files in Python?
A) csv
B) pandas
C) json
D) pickle
Answer: A
What will file.readlines() return?
A) A single string
B) List of lines
C) Dictionary
D) Set of lines
Answer: B
Which of these is the correct way to open a file in write mode?
A) open('file.txt', 'r')
B) open('file.txt', 'a')
C) open('file.txt', 'w')
D) open('file.txt', 'x')
Answer: C
What does seek(0) do?
A) Skips the first character
B) Moves to the end of the file
C) Moves to the beginning of the file
D) Deletes content
Answer: C
What happens if open() is called on a non-existent file in 'r' mode?
A) A new file is created
B) An empty file is returned
C) An error is thrown
D) File is opened with null content
Answer: C
How do you close a file?
A) close(file)
B) file.close()
C) file.end()
D) end(file)
Answer: B
Which method is used to read one line at a time from a file?
A) file.read()
B) file.readline()
C) file.readword()
D) file.readchar()
Answer: B
What does 'a' mode do?
A) Appends to a file
B) Deletes file contents
C) Reads from start
D) Randomly accesses data
Answer: A
What is the extension of a binary file?
A) .txt
B) .csv
C) .bin
D) .binary
Answer: C
Which function in CSV module writes data row-wise?
A) writerow()
B) writer()
C) writeline()
D) write()
Answer: A
In csv.reader(), what data type is each row returned as?
A) dict
B) list
C) tuple
D) string
Answer: B
What does with open() ensure?
A) Multiple files can be opened
B) Automatic file closure
C) Read-only mode
D) File can be appended
Answer: B
What will pickle.load() do?
A) Read a text file
B) Serialize an object
C) Deserialize a binary object
D) Write a CSV file
Answer: C
What is the default delimiter in csv.writer()?
A) Space
B) Tab
C) Comma
D) Pipe
Answer: C
What type of error occurs when reading a binary file in text mode?
A) ValueError
B) FileNotFoundError
C) UnicodeDecodeError
D) TypeError
Answer: C
What is flush() used for?
A) Clears the file
B) Updates file buffer to disk
C) Closes the file
D) Deletes a file
Answer: B
Output-Based Questions (20)
Predict the output or identify the error if any.
1.
python
f = open("demo.txt", "w")
f.write("Hello\nWorld")
f.close()
Output: (No output, writes to file)
2.
python
f = open("demo.txt", "r")
print(f.read())
f.close()
Output:
nginx
Hello
World
3.
python
with open("data.txt", "a") as f:
f.write("New line\n")
Output: Appends "New line" to the end of data.txt
4.
python
f = open("file.txt", "r")
print(f.readline())
print(f.readline())
f.close()
Output: First two lines of the file
5.
python
f = open("sample.txt", "r")
print(f.readlines())
f.close()
Output: List of all lines in the file
6.
python
import csv
with open("data.csv", newline="") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Output: Prints each row as a list
7.
python
import pickle
data = {"name": "John", "age": 30}
with open("data.pkl", "wb") as f:
pickle.dump(data, f)
Output: (Binary file created with pickled data)
8.
python
with open("binaryfile.bin", "rb") as f:
print(f.read())
Output: Binary content of the file
9.
python
f = open("nonexistent.txt", "r")
print(f.read())
Output: FileNotFoundError
10.
python
f = open("demo.txt", "w")
f.write("ABC")
f.seek(0)
print(f.read())
f.close()
Output: io.UnsupportedOperation: not readable
11.
python
f = open("demo.txt", "w+")
f.write("Python")
f.seek(0)
print(f.read())
Output: Python
12.
python
f = open("demo.txt", "a")
f.write(" again")
f.close()
Output: Appends " again" at the end
13.
python
with open("numbers.txt", "w") as f:
for i in range(3):
f.write(f"{i}\n")
Output: File with contents:
0
1
2
14.
python
import csv
with open("info.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["name", "age"])
writer.writerow(["Alice", "25"])
Output: info.csv created with 2 rows
15.
python
import pickle
with open("data.pkl", "rb") as f:
obj = pickle.load(f)
print(obj)
Output: {'name': 'John', 'age': 30}
16.
python
f = open("file.txt", "r")
for line in f:
print(line.strip())
f.close()
Output: Lines printed without newline characters
17.
python
f = open("file.txt", "r")
print(len(f.read()))
f.close()
Output: Character count in the file
18.
python
f = open("file.txt", "r")
print(f.tell())
f.close()
Output: 0 (at the beginning)
19.
python
f = open("file.txt", "r")
f.seek(5)
print(f.read(3))
f.close()
Output: 3 characters from the 6th position
20.
python
f = open("demo.txt", "x")
f.write("Hello")
f.close()
Output: Creates file only if it does not exist; else, throws FileExistsError
🔹 Part B: Python Programming Questions (20)
1. Write a program to count the number of lines in a text file.
2. Write a Python script to read a file and print only even-numbered lines.
3. Write a program to reverse the content of a file and save to another.
4. Append user input to a file.
5. Read a binary file and count number of bytes.
6. Copy contents of one file into another.
7. Write a program to check whether a file exists before reading.
8. Create a CSV file with 5 student records (name, age, grade).
9. Read a CSV file and print records whose grade is above 90.
10. Write a function to serialize and deserialize a dictionary using pickle.
11. Write a program to search a word in a file and count its frequency.
12. Create a text file and write multiplication table of 5 into it.
13. Read a file and remove all whitespaces from it.
14. Convert a CSV file to a list of dictionaries.
15. Program to merge contents of two text files into a third one.
16. Write a program to copy binary content (like image) from one file to another.
17. Create a program that overwrites only the first line of a file.
18. Write code to rename a file using os module.
19. Extract file extension using Python.
20. Write a script to get file size in bytes.
🔹 Part C: Short Answer Questions (20)
1. What is the difference between text and binary files?
2. What does the 'r' and 'w' mode in open() do?
3. How can you read all lines of a file into a list?
4. Explain with open() statement.
5. What is the use of seek() and tell()?
6. How does Python handle file not found errors?
7. What is a CSV file? How is it different from text files?
8. Explain how to use csv.reader() and csv.writer().
9. What is pickling in Python?
10. What module do you use for binary file operations?
11. How is data stored in a binary file?
12. How do you append data to an existing file?
13. What does file.readline() return when the end of the file is reached?
14. Can you open a file in both read and write mode? How?
15. What is the difference between read(), readline(), and readlines()?
16. How can you delete a file using Python?
17. What is the default encoding used by open()?
18. How do you handle large files in Python?
19. What is the use of newline='' in csv.writer()?
20. How to read a CSV file as a dictionary?