Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
66.
What is the purpose of the file.readable() method?
Checks if the file is open for reading
Reads the file content
Checks if the file is a readable text file
Reads the file in binary mode
Answer: Option
Explanation:
file.readable() checks if the file is open for reading.

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

68.
What does the shutil.copy2() function do?
Copies a file and preserves its metadata
Copies a file and renames it
Moves a file to a different directory
Copies a directory and its contents
Answer: Option
Explanation:
shutil.copy2() copies a file and preserves its metadata.

69.
How can you read and print the lines containing at least three digits from a file named "text.txt"?
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)
print_lines_with_digits("text.txt", 3)
with open("text.txt", "r") as file:
    print(file.read("\d{3,}"))
with open("text.txt", "r") as file:
    for line in file:
        if line.count('\d') >= 3:
            print(line)
Answer: Option
Explanation:
Using sum(c.isdigit() for c in line) to count digits in each line.

70.
How can you write a list of dictionaries to a CSV file named "data.csv"?
write_csv("data.csv", [{"key1": "value1"}, {"key2": "value2"}])
with open("data.csv", "w") as file:
    write_csv(file, [{"key1": "value1"}, {"key2": "value2"}])
csv.write("data.csv", [{"key1": "value1"}, {"key2": "value2"}])
with open("data.csv", "w") as file:
    csv.writer(file).write([{"key1": "value1"}, {"key2": "value2"}])
Answer: Option
Explanation:
Using a context manager to open the file and csv.writer() to write a list of dictionaries to a CSV file.