Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
101.
What does the file.writelines(lines) method do?
Writes a single line to the file
Writes multiple lines to the file from a list
Writes the entire content of another file
Writes a specific number of characters to the file
Answer: Option
Explanation:
file.writelines(lines) writes multiple lines to the file from a list.

102.
How can you read and print the lines containing the word "error" from a log file named "logfile.txt"?
with open("logfile.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        if "error" in line.lower():
            print(line)
print_error_lines("logfile.txt")
with open("logfile.txt", "r") as file:
    print(file.read("error"))
with open("logfile.txt", "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.

103.
How can you create a new directory named "data_folder" in the current working directory?
os.mkdir("data_folder")
create_directory("data_folder")
shutil.new_dir("data_folder")
os.create_folder("data_folder")
Answer: Option
Explanation:
Using os.mkdir() to create a new directory.