Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
71.
What does the file.mode attribute represent?
Represents the file's size in bytes
Represents the file's modification time
Represents the file's access mode (read, write, etc.)
Represents the file's creation time
Answer: Option
Explanation:
file.mode represents the file's access mode.

72.
How can you read and print the lines containing the word "error" (case-insensitive) from a log file named "error.log"?
with open("error.log", "r") as file:
    lines = file.readlines()
    for line in lines:
        if "error" in line.lower():
            print(line)
print_error_lines("error.log")
with open("error.log", "r") as file:
    print(file.read("error"))
with open("error.log", "r") as file:
    for line in file:
        if "error".casefold() in line:
            print(line)
Answer: Option
Explanation:
Using line.lower() to make the comparison case-insensitive.

73.
What does the file.isatty() method check for?
Checks if the file is a text file
Checks if the file is open for reading
Checks if the file is a binary file
Checks if the file is connected to a terminal device
Answer: Option
Explanation:
file.isatty() checks if the file is connected to a terminal device.

74.
How can you write a list of tuples to a binary file named "data.bin"?
with open("data.bin", "wb") as file:
    tuples = [(1, 'a'), (2, 'b'), (3, 'c')]
    file.write(pickle.dumps(tuples))
binary_write("data.bin", [(1, 'a'), (2, 'b'), (3, 'c')])
with open("data.bin", "ab") as file:
    tuples = [(1, 'a'), (2, 'b'), (3, 'c')]
    file.write(tuples)
write_binary("data.bin", [(1, 'a'), (2, 'b'), (3, 'c')])
Answer: Option
Explanation:
Using open() in binary write mode and pickle.dumps() to write a list of tuples to a binary file.

75.
How can you check if a file named "output.txt" is empty?
if is_empty("output.txt"):
if os.path.getsize("output.txt") == 0:
if file.isempty("output.txt"):
if check_empty("output.txt"):
Answer: Option
Explanation:
Using os.path.getsize() to check if the file size is 0, indicating an empty file.