Explore key concepts of file handling such as file modes, reading and writing operations, and common errors. This quiz is designed to help users strengthen their understanding of safe, efficient file management across programming environments.
When opening a file in write mode ('w'), what happens if the target file already exists in the directory?
Explanation: Opening a file in write mode ('w') will erase all its existing contents and start with a fresh, empty file before writing new data. Appending data retains existing content but 'w' does not. No error is thrown if the file exists; instead, the data is overwritten. Files are not renamed by default during this operation.
What is the primary purpose of closing a file after performing read or write operations in a program?
Explanation: Closing a file finalizes any pending operations, ensuring all data is flushed to disk and system resources are freed for other tasks. It does not delete or lock the file; the other options misrepresent the close operation. Program restarts are unrelated to file closing.
If a program tries to open a file named 'report.txt' for reading but the file does not exist, what type of error is most likely thrown?
Explanation: Attempting to read a non-existent file typically leads to a file not found error, which stops the operation unless handled. Permission errors refer to access rights, not file existence, and data type or memory errors are unrelated to file opening in this context.
Which approach is generally best when you need to process a very large text file line by line without loading the whole file into memory at once?
Explanation: Processing each line in a loop allows for efficient handling of large files, using minimal memory since only one line is held at a time. Reading the entire file or copying it to memory is inefficient and can cause issues with large files. Global variables do not solve the memory issue and may introduce other problems.
When writing data to a file in binary mode instead of text mode, what is a key difference in how the data is handled?
Explanation: In binary mode, data is written exactly as provided, with no automatic conversion of characters or line endings. Encryption or compression are separate concerns and do not occur by default in either mode. Text mode is not limited to numbers but performs character encoding and conversions.