What will be the output of the following Python code?
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
for index in range(5):
line = fo.next()
print "Line No %d - %s" % (index, line)
# Close opened file
fo.close()
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
for index in range(5):
line = fo.next()
print "Line No %d - %s" % (index, line)
# Close opened file
fo.close()A. Compilation Error
B. Syntax Error
C. Displays Output
D. None of the mentioned
Answer: Option C
How do you open a file named data.txt in read mode in Python?
A. file = open('data.txt', 'r')
B. file = open('data.txt', 'read')
C. file = open('data.txt', 'read mode')
D. file = open('data.txt')
What is the purpose of the with statement in file handling?
A. It ensures that the file is properly closed after usage
B. It creates a new file
C. It reads the file contents
D. It deletes the file
How can you write data to a file in Python?
A. By using the write() method on a file object
B. By using the save() function
C. By using the put() function
D. By using the append() method
What does the read() method of a file object do?
A. It reads the entire contents of the file
B. It writes data to the file
C. It closes the file
D. It deletes the file

Join The Discussion