File Handling in Python MCQs Exercise I


Ques 1 File Handling


What is the purpose of the open() function in Python?
  a) To create a new file
  b) To read the contents of a file
  c) To write data to a file
  d) All of the above


d is the correct option





Ques 2 File Handling


Which mode is used to open a file for writing in Python?
  a) 'r'
  b) 'w'
  c) 'a'
  d) 'x'


b is the correct option





Ques 3 File Handling


What will be the output of the following Python code snippet?

file = open("filename.txt", "a")
file.write("This is an appended line.")
file.close()

  a) Deletes the contents of the file
  b) Creates a new file and writes "This is an appended line." to it
  c) Appends "This is an appended line." to the existing contents of the file
  d) Prints "This is an appended line."


c is the correct option





Ques 4 File Handling


What will be the output of the following Python code snippet?

file = open("filename.txt", "r")
content = file.read()
file.close()
print(content)

  a) Error: File does not exist
  b) Prints the contents of the file
  c) Error: File is not open for reading
  d) None of the above


b is the correct option





Ques 5 File Handling


What does the 'with' statement do in file handling?
  a) Ensures proper file closure even if an exception occurs
  b) Renames a file
  c) Deletes the contents of a file
  d) Opens a file for writing


b is the correct option





Ques 6 File Handling


What will be the output of the following Python code snippet?

file = open("filename.txt", "w")
file.write("Hello, World!")
file.close()

  a) Reads the contents of the file
  b) Appends text to the file
  c) Creates a new file and writes "Hello, World!" to it
  d) Renames the file to "Hello, World!"


c is the correct option