Exercise: Python

Questions for: Reading And Writing Files

What does the file.isatty() method check for?
A:
Checks if the file is a text file
B:
Checks if the file is open for reading
C:
Checks if the file is a binary file
D:
Checks if the file is connected to a terminal device
Answer: D
file.isatty() checks if the file is connected to a terminal device.
How can you read and print the lines containing the word "error" (case-insensitive) from a log file named "error.log"?
A:
with open("error.log", "r") as file:
    lines = file.readlines()
    for line in lines:
        if "error" in line.lower():
            print(line)
B:
print_error_lines("error.log")
C:
with open("error.log", "r") as file:
    print(file.read("error"))
D:
with open("error.log", "r") as file:
    for line in file:
        if "error".casefold() in line:
            print(line)
Answer: A
Using line.lower() to make the comparison case-insensitive.
What does the file.mode attribute represent?
A:
Represents the file's size in bytes
B:
Represents the file's modification time
C:
Represents the file's access mode (read, write, etc.)
D:
Represents the file's creation time
Answer: C
file.mode represents the file's access mode.
How can you read and print the lines containing at least three digits from a file named "text.txt"?
A:
with open("text.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        if sum(c.isdigit() for c in line) >= 3:
            print(line)
B:
print_lines_with_digits("text.txt", 3)
C:
with open("text.txt", "r") as file:
    print(file.read("\d{3,}"))
D:
with open("text.txt", "r") as file:
    for line in file:
        if line.count('\d') >= 3:
            print(line)
Answer: A
Using sum(c.isdigit() for c in line) to count digits in each line.
What does the shutil.copy2() function do?
A:
Copies a file and preserves its metadata
B:
Copies a file and renames it
C:
Moves a file to a different directory
D:
Copies a directory and its contents
Answer: A
shutil.copy2() copies a file and preserves its metadata.
Ad Slot (Above Pagination)
Quiz