Exercise: Python

Questions for: Reading And Writing Files

How can you read and print the lines containing the word "Python" in a case-insensitive manner from a file named "code.txt"?
A:
with open("code.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        if "Python" in line.lower():
            print(line)
B:
print_python_lines("code.txt")
C:
with open("code.txt", "r") as file:
    print(file.read("Python"))
D:
with open("code.txt", "r") as file:
    for line in file:
        if "Python".casefold() in line:
            print(line)
Answer: A
Using line.lower() to make the comparison case-insensitive.
What is the purpose of the file.readable() method?
A:
Checks if the file is open for reading
B:
Reads the file content
C:
Checks if the file is a readable text file
D:
Reads the file in binary mode
Answer: A
file.readable() checks if the file is open for reading.
How can you check if a file named "data.csv" is a valid CSV file?
A:
if is_valid_csv("data.csv"):
B:
if is_csv_file("data.csv"):
C:
if validate_csv("data.csv"):
D:
if os.path.iscsv("data.csv"):
Answer: B
Checking if a file has a CSV extension to determine if it's a valid CSV file.
How can you create a new text file named "new_file.txt" and write the text "Hello, World!" to it?
A:
new_file("new_file.txt", "Hello, World!")
B:
with open("new_file.txt", "w") as file:
    write_text(file, "Hello, World!")
C:
text.write("new_file.txt", "Hello, World!")
D:
with open("new_file.txt", "w") as file:
    file.write("Hello, World!")
Answer: D
Using a context manager to open the file and writing the text to it.
What is the purpose of the file.writelines() method?
A:
Writes a list of strings to a file
B:
Writes the buffered data to the file
C:
Writes a list of dictionaries to a file
D:
Writes a list of numbers to a file
Answer: A
file.writelines() writes a list of strings to a file.
Ad Slot (Above Pagination)
Quiz