Exercise: Python

Questions for: Reading And Writing Files

What does the file.fileno() method return?
A:
Returns the file's size in bytes
B:
Returns the file's access mode
C:
Returns the file's file descriptor
D:
Returns the file's encoding
Answer: C
file.fileno() returns the file's file descriptor.
How can you read and print the lines containing the word "success" or "failure" from a log file named "logfile.txt"?
A:
with open("logfile.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        if "success" in line.lower() or "failure" in line.lower():
            print(line)
B:
print_log_lines("logfile.txt", ["success", "failure"])
C:
with open("logfile.txt", "r") as file:
    print(file.read("success" or "failure"))
D:
with open("logfile.txt", "r") as file:
    for line in file:
        if "success".casefold() in line or "failure".casefold() in line:
            print(line)
Answer: A
Using line.lower() to make the comparison case-insensitive.
What does the file.encoding attribute represent?
A:
Represents the file's access mode
B:
Represents the file's size in bytes
C:
Represents the file's encoding (character set)
D:
Represents the file's creation time
Answer: C
file.encoding represents the file's encoding.
How can you check if a file named "output.txt" is empty?
A:
if is_empty("output.txt"):
B:
if os.path.getsize("output.txt") == 0:
C:
if file.isempty("output.txt"):
D:
if check_empty("output.txt"):
Answer: B
Using os.path.getsize() to check if the file size is 0, indicating an empty file.
How can you write a list of tuples to a binary file named "data.bin"?
A:
with open("data.bin", "wb") as file:
    tuples = [(1, 'a'), (2, 'b'), (3, 'c')]
    file.write(pickle.dumps(tuples))
B:
binary_write("data.bin", [(1, 'a'), (2, 'b'), (3, 'c')])
C:
with open("data.bin", "ab") as file:
    tuples = [(1, 'a'), (2, 'b'), (3, 'c')]
    file.write(tuples)
D:
write_binary("data.bin", [(1, 'a'), (2, 'b'), (3, 'c')])
Answer: A
Using open() in binary write mode and pickle.dumps() to write a list of tuples to a binary file.
Ad Slot (Above Pagination)
Quiz