Exercise: Python

Questions for: Reading And Writing Files

How can you read and print the last 10 lines from a file named "log.txt"?
A:
with open("log.txt", "r") as file:
    lines = file.readlines()
    for line in lines[-10:]:
        print(line)
B:
print_last_lines("log.txt", 10)
C:
with open("log.txt", "r") as file:
    print(file.tail(10))
D:
with open("log.txt", "r") as file:
    for line in file:
        if line.number() > len(file) - 10:
            print(line)
Answer: A
Using list slicing to get the last 10 lines and printing them.
What does the file.seek() method do?
A:
Closes the file
B:
Moves the file cursor to a specified position
C:
Reads the file content
D:
Truncates the file at the current position
Answer: B
file.seek() moves the file cursor to a specified position.
How can you remove a file named "data.txt"?
A:
remove_file("data.txt")
B:
os.remove("data.txt")
C:
delete_file("data.txt")
D:
file.delete("data.txt")
Answer: B
Using os.remove() to remove a file in Python.
How can you write a dictionary to a JSON file named "config.json"?
A:
write_json("config.json", {"key": "value"})
B:
with open("config.json", "w") as file:
    write_json(file, {"key": "value"})
C:
json.write("config.json", {"key": "value"})
D:
with open("config.json", "w") as file:
    json.dump({"key": "value"}, file)
Answer: D
Using open() in write mode and json.dump() to write a dictionary to a JSON file.
What is the purpose of the file.truncate() method?
A:
Closes the file
B:
Truncates the file at the current position
C:
Reads the file content
D:
Writes the buffered data to the file
Answer: B
file.truncate() truncates the file at the current position.
Ad Slot (Above Pagination)
Quiz