Exercise: Reading And Writing Files

Questions for: Reading And Writing Files

What is the purpose of the seek() method when working with files?
A:
To check if a file exists
B:
To move the file cursor to a specific position
C:
To read the contents of a file
D:
To close a file
Answer: B
The seek() method is used to move the file cursor to a specified position in the file.
In Python, what does the with statement provide when working with files?
A:
It opens a file in write mode
B:
It automatically closes the file after operations
C:
It reads the contents of a file
D:
It appends data to a file
Answer: B
The with statement is used for efficient file handling and automatically closes the file when the block is exited.
How can you close a file in Python after performing operations on it?
A:
file.close()
B:
close_file(file)
C:
file.end()
D:
end_file(file)
Answer: A
To close a file in Python, you should use the close() method on the file object.
What is the purpose of the write() method when used with a file object?
A:
To create a new file
B:
To read the contents of a file
C:
To write data to a file
D:
To close a file
Answer: C
The write() method is used to write data to a file in Python.
How can you read the entire contents of a file named "data.txt" into a string?
A:
content = read_file("data.txt")
B:
content = open("data.txt").read()
C:
content = file.read("data.txt")
D:
content = open_file("data.txt", "r")
Answer: B
Using the read() method on the file object reads the entire contents of the file into a string.
Ad Slot (Above Pagination)
Quiz