Exercise: Reading And Writing Files

Questions for: Reading And Writing Files

How can you read and print the contents of a binary file named "binary.dat"?
A:
with open("binary.dat", "rb") as file:
    print(file.read())
B:
print_binary_content("binary.dat")
C:
with open("binary.dat", "r") as file:
    print(file.read())
D:
with open("binary.dat", "rb") as file:
    print(file.readlines())
Answer: A
Using open() in binary read mode to read and print the binary content.
What does the file.is_closed attribute check for?
A:
Checks if the file is open for reading
B:
Checks if the file is a binary file
C:
Checks if the file is a text file
D:
Checks if the file is closed
Answer: D
file.is_closed checks if the file is closed.
How can you write a dictionary to a JSON file named "data.json"?
A:
with open("data.json", "w") as file:
    json.dump(my_dict, file)
B:
write_json("data.json", my_dict)
C:
with open("data.json", "w") as file:
    file.write(json.dumps(my_dict))
D:
write_to_json("data.json", my_dict)
Answer: A
Using json.dump() to write a dictionary to a JSON file.
What is the purpose of the file.mode attribute?
A:
Represents the file's modification time
B:
Represents the file's size in bytes
C:
Represents the file's access mode (read, write, etc.)
D:
Represents the file's encoding (character set)
Answer: C
file.mode represents the file's access mode.
How can you check if a file named "output.txt" is writable?
A:
if is_writable("output.txt"):
B:
if file.can_write("output.txt"):
C:
if os.access("output.txt", os.W_OK):
D:
if check_writable("output.txt"):
Answer: C
Using os.access() with the os.W_OK flag to check if the file is writable.
Ad Slot (Above Pagination)
Quiz