Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
1.
How can you open a file named "example.txt" in Python for reading?
open("example.txt", "w")
open("example.txt", "r")
open("example.txt", "a")
open("example.txt", "x")
Answer: Option
Explanation:
To open a file for reading, you should use the mode "r" in the open() function.

2.
How can you read the entire contents of a file named "data.txt" into a string?
content = read_file("data.txt")
content = open("data.txt").read()
content = file.read("data.txt")
content = open_file("data.txt", "r")
Answer: Option
Explanation:
Using the read() method on the file object reads the entire contents of the file into a string.

3.
What is the purpose of the write() method when used with a file object?
To create a new file
To read the contents of a file
To write data to a file
To close a file
Answer: Option
Explanation:
The write() method is used to write data to a file in Python.

4.
How can you close a file in Python after performing operations on it?
file.close()
close_file(file)
file.end()
end_file(file)
Answer: Option
Explanation:
To close a file in Python, you should use the close() method on the file object.

5.
In Python, what does the with statement provide when working with files?
It opens a file in write mode
It automatically closes the file after operations
It reads the contents of a file
It appends data to a file
Answer: Option
Explanation:
The with statement is used for efficient file handling and automatically closes the file when the block is exited.