File Handling
readline() reads one line from a text file that has been opened for reading. It returns the line as a string and moves the file position on, so the next call to readline() returns the line after it. Reading one line at a time lets you deal with each record as you go instead of loading the whole file at once.
Newline character: the string that comes back still contains the "\n" character that marked the end of the line in the file. You cannot see it on screen, but it is part of the string, so printing the line straight away leaves the cursor on the next line.
strip() returns a copy of the string with the whitespace taken off both ends, which means the newline plus any spaces or tabs. Apply it as soon as the line has been read so that comparisons work as you expect: a line holding Jazz will not equal "Jazz" while the newline is still attached.
End of file is the point where the reader has taken every line the file holds. A further call to readline() then returns an empty string "", a string with nothing in it at all. That is not the same as a blank line partway down the file: a blank line still ends in a newline character, so it comes back as "\n", which is not empty.
strip() only tidies the text, it does not turn it into a number. If the line holds a price or a score, cast it with int() or float() before you do arithmetic with it.
A string holding a newline behaves in the same way as a line returned by readline():
line = "Jazz\n" # the kind of string readline() returns for the line Jazz
print(line) # the newline inside the string ends the output line
print(line.strip()) # strip() copies the string without the newline
print(len(line)) # the newline counts as a character
print(len(line.strip())) # fewer characters once it has goneOutput:
Jazz
Jazz
5
4 OCR GCSE Computer Science · File Handling