Exercise: Python

Questions for: Reading And Writing Files

How can you read and print the lines with odd line numbers from a file named "numbers.txt"?
A:
with open("numbers.txt", "r") as file:
    lines = file.readlines()
    for i in range(len(lines)):
        if i % 2 != 0:
            print(lines[i])
B:
print_odd_lines("numbers.txt")
C:
with open("numbers.txt", "r") as file:
    print(file.read(2))
D:
with open("numbers.txt", "r") as file:
    for line in file:
        if line.number() % 2 != 0:
            print(line)
Answer: A
Using the index to identify odd line numbers and printing corresponding lines.
What does the os.path.join() function do?
A:
Joins two paths into a single path
B:
Checks if a path is a regular file
C:
Returns the base name of a file or directory
D:
Moves a file to a different directory
Answer: A
os.path.join() joins two paths into a single path.
How can you copy the contents of a file named "source.txt" to another file named "destination.txt"?
A:
shutil.move("source.txt", "destination.txt")
B:
copy_file("source.txt", "destination.txt")
C:
with open("destination.txt", "w") as dest:
    dest.write(open("source.txt").read())
D:
rename_file("source.txt", "destination.txt")
Answer: C
Using a context manager to open both files and writing the content of "source.txt" to "destination.txt".
How can you read and print the lines from a file named "book.txt" in reverse order?
A:
with open("book.txt", "r") as file:
    lines = file.readlines()
    for line in reversed(lines):
        print(line)
B:
print_reverse_lines("book.txt")
C:
with open("book.txt", "r") as file:
    print(file.read()[::-1])
D:
with open("book.txt", "r") as file:
    lines = file.readlines()
    for line in lines.reverse():
        print(line)
Answer: A
Using reversed() to iterate through lines in reverse order.
What does the os.path.splitext() function return?
A:
Returns the file's extension
B:
Returns the file's base name
C:
Returns the file's absolute path
D:
Returns the file's creation time
Answer: A
os.path.splitext() returns the file's extension.
Ad Slot (Above Pagination)
Quiz