Exercise: Python

Questions for: Reading And Writing Files

How can you append a list of numbers to a binary file named "data.bin"?
A:
with open("data.bin", "wb") as file:
    numbers = [1, 2, 3, 4, 5]
    file.write(bytes(numbers))
B:
append_binary("data.bin", [1, 2, 3, 4, 5])
C:
with open("data.bin", "ab") as file:
    numbers = [1, 2, 3, 4, 5]
    file.write(numbers)
D:
binary_append("data.bin", [1, 2, 3, 4, 5])
Answer: A
Using open() in binary write mode and bytes() to write a list of numbers to a binary file.
What is the purpose of the file.flush() method?
A:
Writes the buffered data to the file
B:
Closes the file
C:
Reads the file content
D:
Moves the file cursor to the beginning
Answer: A
file.flush() writes the buffered data to the file.
How can you read and print the lines containing both "Python" and "programming" from a file named "code.txt"?
A:
with open("code.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        if "Python" in line and "programming" in line:
            print(line)
B:
print_python_programming_lines("code.txt")
C:
with open("code.txt", "r") as file:
    print(file.read("Python programming"))
D:
with open("code.txt", "r") as file:
    for line in file:
        if "Python" in line:
            print(line)
        elif "programming" in line:
            print(line)
Answer: A
Using in to check for both "Python" and "programming" in each line.
How can you check if a file named "data.xml" is a valid XML file?
A:
if is_valid_xml("data.xml"):
B:
if is_xml_file("data.xml"):
C:
if validate_xml("data.xml"):
D:
if os.path.isxml("data.xml"):
Answer: B
Checking if a file has an XML extension to determine if it's a valid XML file.
What does the os.path.getctime() function return?
A:
Returns the file's creation time
B:
Returns the file's size in bytes
C:
Returns the file's absolute path
D:
Returns the file's modification time
Answer: A
os.path.getctime() returns the creation time of a file.
Ad Slot (Above Pagination)
Quiz