Exercise: Python

Questions for: Reading And Writing Files

What is the purpose of the os.path.join() function in Python when working with file paths?
A:
To create a new file
B:
To concatenate multiple file paths
C:
To check if a file exists
D:
To rename a file
Answer: B
os.path.join() is used to concatenate multiple file paths and create a valid path.
How can you write a dictionary to a file named "data.json" in JSON format?
A:
write_json("data.json", {"key": "value"})
B:
json.write("data.json", {"key": "value"})
C:
with open("data.json", "w") as file:
    json.dump({"key": "value"}, file)
D:
file.write_json("data.json", {"key": "value"})
Answer: C
Using json.dump() to write a dictionary to a JSON file.
What is the purpose of the truncate() method when working with files?
A:
To remove all contents of the file
B:
To shorten the file name
C:
To create a new file
D:
To split the file into multiple parts
Answer: A
The truncate() method is used to remove all contents of the file from the current position.
Which method is used to check if a file object is in a valid state?
A:
validate()
B:
check()
C:
is_valid()
D:
closed()
Answer: D
The closed() method checks if a file object is in a valid state (closed or not).
How can you read and print only the even-numbered lines from a file named "numbers.txt"?
A:
even_lines = open("numbers.txt").readlines()[1::2]
    for line in even_lines:
    print(line)
B:
with open("numbers.txt", "r") as file:
    lines = file.readlines()
    for i in range(1, len(lines), 2):
        print(lines[i])
C:
even_numbers("numbers.txt")
D:
read_even("numbers.txt")
Answer: A
Using list slicing to select even-numbered lines and then printing them.
Ad Slot (Above Pagination)
Quiz