Exercise: Python

Questions for: Reading And Writing Files

How can you read and print the last 3 lines from a file named "data.txt"?
A:
with open("data.txt", "r") as file:
    lines = file.readlines()
    print(lines[-3:])
B:
print_last_lines("data.txt", 3)
C:
with open("data.txt", "r") as file:
    print(file.read(-3))
D:
with open("data.txt", "r") as file:
    for line in file:
        print(line[-3:])
Answer: A
Using lines[-3:] to get the last 3 lines from the list of lines.
What does the file.writelines() method do?
A:
Writes a single line to the file
B:
Writes multiple lines to the file from a list
C:
Writes the entire content of another file
D:
Writes a specific number of characters to the file
Answer: B
file.writelines() writes multiple lines to the file from a list.
How can you write a list of strings to a text file named "output.txt" in Python, with each string on a new line?
A:
with open("output.txt", "w") as file:
    strings = ["Hello", "World", "Python"]
    file.write("\n".join(strings))
B:
write_lines("output.txt", ["Hello", "World", "Python"])
C:
text.write("output.txt", ["Hello", "World", "Python"])
D:
with open("output.txt", "w") as file:
    file.writelines(["Hello", "World", "Python"])
Answer: A
Using "\n".join(strings) to join the strings with newline characters.
What does the os.path.abspath() function do?
A:
Returns the absolute path of the current working directory
B:
Returns the relative path of the specified file
C:
Returns the absolute path of the specified file
D:
Checks if a file exists in the current directory
Answer: A
os.path.abspath() returns the absolute path of the current working directory.
How can you read and print the first 5 characters from a file named "sample.txt"?
A:
with open("sample.txt", "r") as file:
    print(file.read(5))
B:
print_first_characters("sample.txt", 5)
C:
with open("sample.txt", "r") as file:
    print(file.readline(5))
D:
with open("sample.txt", "r") as file:
    print(file.read(1, 5))
Answer: A
Using file.read(5) to read the first 5 characters.
Ad Slot (Above Pagination)
Quiz