Python File Handling MCQs Guide
Python File Handling MCQs Guide
The 'read()' method reads the entire content of a file as a single string, while 'readline()' reads one line at a time from a file. These methods are used based on whether the entire file content or specific lines are needed for processing .
Using 'rb' mode opens a file for reading in binary format as opposed to text when using 'r'. This is significant when dealing with non-textual data, such as images or executable files, where preserving the exact byte sequence is necessary for correct data processing .
The 'writelines()' method writes a list of strings to a file without adding any newline characters between each string. In contrast, 'write()' writes a single string to the file and nothing else. If multiple lines are to be written with 'write()', newline characters must be manually included at the end of each string .
The 'with' statement in file handling is beneficial because it ensures that a file is properly closed after its suite is finished, even if an exception is raised. This is important for managing system resources efficiently and prevents resource leaks such as open file descriptors .
To open a file for writing in binary mode, the mode 'wb' should be used. If the file already exists, it will be overwritten and the existing data will be lost .
When attempting to open a file that does not exist using 'r' mode, a FileNotFoundError is raised because 'r' mode is intended for reading, and it is assumed the file is already present. Thus, if the file cannot be found, the operation fails .
Not using the 'close()' method after file operations can lead to resource leaks wherein the file remains open and occupies file descriptors, potentially leading to the exhaustion of resources especially in long-running applications or when many files are handled concurrently. It is essential to free system resources by closing files properly or use the 'with' statement which handles closure automatically .
The 'seek(0)' function moves the file cursor to the beginning of the file. This is useful when you need to re-read the file from the start after reading or writing operations have changed the cursor position .
The 'tell()' method returns the current position of the file cursor in the file, which helps in tracking how much data has been processed and serves as a reference point for further read or write operations .
The assertion states that binary files store data in human-readable format is false, whereas the reason correctly states that binary files use binary encoding (0s and 1s) for storing data. This means binary files are not directly readable by humans unless decoded properly, making the assertion false and the reason true .