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

Ques 2 File Handling


Which mode is used to open a file for writing in Python?

A 'r'
B 'w'
C 'a'
D 'x'

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."

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

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

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!"