Exercise: Reading And Writing Files

Questions for: Reading And Writing Files

In Python, what is the purpose of the tell() method when working with files?
A:
To check if a file is readable
B:
To get the current position of the file cursor
C:
To retrieve the total number of characters in a file
D:
To close a file
Answer: B
The tell() method returns the current position of the file cursor.
How can you check if a file named "data.txt" exists in a directory using Python?
A:
file_exists("data.txt")
B:
if not exists("data.txt"):
C:
os.path.exists("data.txt")
D:
if "data.txt" in os.listdir():
Answer: C
The os.path.exists() function checks if a file exists in a directory.
How can you write a list of strings to a file named "output.txt"?
A:
write_file("output.txt", ["line1", "line2", "line3"])
B:
file.write(["line1", "line2", "line3"])
C:
write_lines("output.txt", ["line1", "line2", "line3"])
D:
with open("output.txt", "w") as file: file.writelines(["line1", "line2", "line3"])
Answer: D
The writelines() method is used to write a list of strings to a file in Python.
What does the readline() method do in Python when working with files?
A:
Reads the entire contents of the file
B:
Reads one line from the file
C:
Reads the first character of the file
D:
Reads the last line of the file
Answer: B
The readline() method is used to read a single line from the file.
Which of the following modes is used to open a file in Python for both reading and writing?
A:
"r"
B:
"w"
C:
"a"
D:
"r+"
Answer: D
The mode "r+" allows both reading and writing operations on a file.
Ad Slot (Above Pagination)
Quiz