Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
51.
What is the purpose of the file.flush() method?
Writes the buffered data to the file
Closes the file
Reads the file content
Moves the file cursor to the beginning
Answer: Option
Explanation:
file.flush() writes the buffered data to the file.

52.
How can you append a list of numbers to a binary file named "data.bin"?
with open("data.bin", "wb") as file:
    numbers = [1, 2, 3, 4, 5]
    file.write(bytes(numbers))
append_binary("data.bin", [1, 2, 3, 4, 5])
with open("data.bin", "ab") as file:
    numbers = [1, 2, 3, 4, 5]
    file.write(numbers)
binary_append("data.bin", [1, 2, 3, 4, 5])
Answer: Option
Explanation:
Using open() in binary write mode and bytes() to write a list of numbers to a binary file.

53.
What does the os.path.splitext() function return?
Returns the file's extension
Returns the file's base name
Returns the file's absolute path
Returns the file's creation time
Answer: Option
Explanation:
os.path.splitext() returns the file's extension.

54.
How can you read and print the lines from a file named "book.txt" in reverse order?
with open("book.txt", "r") as file:
    lines = file.readlines()
    for line in reversed(lines):
        print(line)
print_reverse_lines("book.txt")
with open("book.txt", "r") as file:
    print(file.read()[::-1])
with open("book.txt", "r") as file:
    lines = file.readlines()
    for line in lines.reverse():
        print(line)
Answer: Option
Explanation:
Using reversed() to iterate through lines in reverse order.

55.
How can you copy the contents of a file named "source.txt" to another file named "destination.txt"?
shutil.move("source.txt", "destination.txt")
copy_file("source.txt", "destination.txt")
with open("destination.txt", "w") as dest:
    dest.write(open("source.txt").read())
rename_file("source.txt", "destination.txt")
Answer: Option
Explanation:
Using a context manager to open both files and writing the content of "source.txt" to "destination.txt".