Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
91.
How can you read and print the last 3 lines from a file named "data.txt"?
with open("data.txt", "r") as file:
    lines = file.readlines()
    print(lines[-3:])
print_last_lines("data.txt", 3)
with open("data.txt", "r") as file:
    print(file.read(-3))
with open("data.txt", "r") as file:
    for line in file:
        print(line[-3:])
Answer: Option
Explanation:
Using lines[-3:] to get the last 3 lines from the list of lines.

92.
What does the file.seek() method do?
Moves the file cursor to a specified position
Reads the entire file content
Closes the file
Moves the file cursor to the beginning
Answer: Option
Explanation:
file.seek() moves the file cursor to a specified position.

93.
How can you check if a file named "output.txt" is writable?
if is_writable("output.txt"):
if file.can_write("output.txt"):
if os.access("output.txt", os.W_OK):
if check_writable("output.txt"):
Answer: Option
Explanation:
Using os.access() with the os.W_OK flag to check if the file is writable.

94.
What is the purpose of the file.mode attribute?
Represents the file's modification time
Represents the file's size in bytes
Represents the file's access mode (read, write, etc.)
Represents the file's encoding (character set)
Answer: Option
Explanation:
file.mode represents the file's access mode.

95.
How can you write a dictionary to a JSON file named "data.json"?
with open("data.json", "w") as file:
    json.dump(my_dict, file)
write_json("data.json", my_dict)
with open("data.json", "w") as file:
    file.write(json.dumps(my_dict))
write_to_json("data.json", my_dict)
Answer: Option
Explanation:
Using json.dump() to write a dictionary to a JSON file.