Reading data often involves the readline() method, which retrieves characters from the current pointer position up to the next newline character (). This is typically used within a loop that continues until an End of File (EOF) marker or an empty string is encountered.
Writing data is performed using methods like write() or writeline(). It is important to manually include newline characters if the data is intended to be stored on separate lines, as many basic write functions do not append them automatically.
The Close operation is the final step in the lifecycle. It flushes any remaining data from the program's buffer to the physical disk and releases the file lock, allowing other applications or users to access the file.
| Feature | Arrays (RAM) | Text Files (Storage) |
|---|---|---|
| Persistence | Lost when program ends | Remains after program ends |
| Capacity | Limited by available RAM | Limited by disk space |
| Access Speed | Extremely fast | Slower (I/O overhead) |
| Structure | Indexed/Keyed | Sequential/Line-based |
It is critical to distinguish between Overwriting and Appending. Overwriting (mode 'w') is a destructive process that resets the file, while Appending (mode 'a') is a constructive process that preserves existing data and adds new information at the end.
Always verify the mode: A common exam mistake is using 'w' when the question asks to 'add' data to a file, which would accidentally delete the existing records. Use 'a' for adding and 'w' only for creating fresh files.
The 'Close' Rule: Examiners often look for the close() command. Even if the logic for reading or writing is perfect, failing to close the file can result in marks being deducted because it represents a memory leak and potential data corruption risk.
Check for EOF: When writing algorithms to read a whole file, ensure there is a clear condition to stop the loop (e.g., while not endOfFile). Without this, the program may enter an infinite loop or crash when it runs out of data.
File Not Found Errors: Students often forget that opening a file in 'r' mode requires the file to already exist in the specified directory. If the path is incorrect or the file is missing, the program will terminate with an exception.
Buffer Lag: Data written to a file is often stored in a temporary 'buffer' in RAM before being committed to the disk. If a program crashes before the close() command is executed, the data in the buffer may never be saved.
Newline Confusion: Many beginners assume that calling a write function multiple times will automatically put each entry on a new line. In reality, most languages require an explicit \n character to move the file pointer to the next line.