CBSE Class XII CS File Handling Questions
CBSE Class XII CS File Handling Questions
A: File handling allows storing data permanently on a disk. It enables reading from and
writing to files, making data persistence possible.
A: Text files store data in human-readable ASCII or Unicode format, while binary files store
data in binary (0s and 1s) form, which is directly readable by machines.
Q: Write a Python code snippet to open a file in write mode, write 'Hello, World!' to it,
and close it.
A: write() writes a single string to the file, while writelines() writes a list of strings to the file
in sequence.
A: The seek() method moves the file pointer to a specific location within the file.
A: def count_words(filename):
with open(filename, "r") as file:
data = file.read()
words = data.split()
return len(words)
filename = "sample.txt"
print("Total words:", count_words(filename))
Q: Describe the process of reading and writing a binary file with an example.
A: def display_high_scorers(filename):
with open(filename, "r") as file:
for line in file:
name, marks = line.strip().split(',')
if int(marks) > 75:
print(name, marks)
A: try:
with open("example.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("File not found. Please check the file path.")
Q: Write a Python program to append data to a file only if it exists; otherwise, create a
new file and write data.
A: try:
with open("data.txt", "a") as file:
file.write("Appended text.\n")
except FileNotFoundError:
with open("data.txt", "w") as file:
file.write("New file created and text added.\n")