Python Programming - Reading and Writing Files

Exercise : Reading and Writing Files - General Questions
  • Reading and Writing Files - General Questions
11.
In Python, what is the purpose of the tell() method when working with files?
To check if a file is readable
To get the current position of the file cursor
To retrieve the total number of characters in a file
To close a file
Answer: Option
Explanation:
The tell() method returns the current position of the file cursor.

12.
What happens if you open a file using the mode "a"?
The file is opened for reading
The file is opened for writing, starting from the beginning
The file is opened for appending, starting from the end
The file is opened for both reading and writing
Answer: Option
Explanation:
The "a" mode opens the file for appending, and the file cursor is positioned at the end.

13.
How can you read and print the first 3 lines of a file named "sample.txt"?
lines = open("sample.txt").readlines()[:3]
    for line in lines:
    print(line)
with open("sample.txt", "r") as file:
    for i in range(3):
        print(file.readline())
contents = read_lines("sample.txt", 3)
print(contents)
first_three_lines("sample.txt")
Answer: Option
Explanation:
Using a for loop with readline() to read and print the first 3 lines.

14.
What does the flush() method do when working with files?
Writes the file contents to the console
Clears the contents of the file
Flushes the internal buffer, ensuring data is written to the file
Closes the file
Answer: Option
Explanation:
The flush() method ensures that any buffered data is written to the file.

15.
How can you copy the contents of one file, "source.txt", to another file, "destination.txt"?
copy_file("source.txt", "destination.txt")
with open("destination.txt", "w") as dest:
    dest.write(open("source.txt").read())
file_copy("source.txt", "destination.txt")
copy_contents("source.txt", "destination.txt")
Answer: Option
Explanation:
Opening both files and using write() to copy the contents from source to destination.