Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
6.
What is the purpose of the seek() method when working with files?
To check if a file exists
To move the file cursor to a specific position
To read the contents of a file
To close a file
Answer: Option
Explanation:
The seek() method is used to move the file cursor to a specified position in the file.

7.
Which of the following modes is used to open a file in Python for both reading and writing?
"r"
"w"
"a"
"r+"
Answer: Option
Explanation:
The mode "r+" allows both reading and writing operations on a file.

8.
What does the readline() method do in Python when working with files?
Reads the entire contents of the file
Reads one line from the file
Reads the first character of the file
Reads the last line of the file
Answer: Option
Explanation:
The readline() method is used to read a single line from the file.

9.
How can you write a list of strings to a file named "output.txt"?
write_file("output.txt", ["line1", "line2", "line3"])
file.write(["line1", "line2", "line3"])
write_lines("output.txt", ["line1", "line2", "line3"])
with open("output.txt", "w") as file: file.writelines(["line1", "line2", "line3"])
Answer: Option
Explanation:
The writelines() method is used to write a list of strings to a file in Python.

10.
How can you check if a file named "data.txt" exists in a directory using Python?
file_exists("data.txt")
if not exists("data.txt"):
os.path.exists("data.txt")
if "data.txt" in os.listdir():
Answer: Option
Explanation:
The os.path.exists() function checks if a file exists in a directory.