Exercise: Python

Questions for: Reading And Writing Files

What is the purpose of the os.remove() function?
A:
To check if a file exists
B:
To remove a directory
C:
To delete a file
D:
To rename a file
Answer: C
The os.remove() function is used to delete a file in Python.
How can you copy the contents of one file, "source.txt", to another file, "destination.txt"?
A:
copy_file("source.txt", "destination.txt")
B:
with open("destination.txt", "w") as dest:
    dest.write(open("source.txt").read())
C:
file_copy("source.txt", "destination.txt")
D:
copy_contents("source.txt", "destination.txt")
Answer: B
Opening both files and using write() to copy the contents from source to destination.
What does the flush() method do when working with files?
A:
Writes the file contents to the console
B:
Clears the contents of the file
C:
Flushes the internal buffer, ensuring data is written to the file
D:
Closes the file
Answer: C
The flush() method ensures that any buffered data is written to the file.
How can you read and print the first 3 lines of a file named "sample.txt"?
A:
lines = open("sample.txt").readlines()[:3]
    for line in lines:
    print(line)
B:
with open("sample.txt", "r") as file:
    for i in range(3):
        print(file.readline())
C:
contents = read_lines("sample.txt", 3)
print(contents)
D:
first_three_lines("sample.txt")
Answer: B
Using a for loop with readline() to read and print the first 3 lines.
What happens if you open a file using the mode "a"?
A:
The file is opened for reading
B:
The file is opened for writing, starting from the beginning
C:
The file is opened for appending, starting from the end
D:
The file is opened for both reading and writing
Answer: C
The "a" mode opens the file for appending, and the file cursor is positioned at the end.
Ad Slot (Above Pagination)
Quiz