LearnWave
Learn it. Master it.

File Handling in Python

Reading, writing and offsets

Use the read and write methods and seek/tell.

Writing to a text file:

  • write(string) writes one string and returns the number of characters written. A newline, '\n', counts as one character. It accepts only strings, so a number must first be converted with str().
  • writelines(sequence) writes every string in an iterable, such as a list of strings. It does not return anything, and does not add newlines by itself.

Reading from a text file:

  • read(n) reads n bytes (characters). With no argument, or a negative one, it reads the whole file.
  • readline(n) reads one line (or up to n bytes of it), including its newline. At the end of the file, it returns an empty string.
  • readlines() reads all the lines and returns them as a list of strings.

Two string methods help when processing what was read: split() breaks a line into a list of words, and splitlines() gives the lines without their newline characters.

Moving the cursor. The file pointer moves forward as data is read or written. Two methods let you find and change its position:

  • tell() returns the cursor's current position, as a number of bytes from the start of the file.
  • seek(offset, reference_point) moves the cursor by offset bytes from the reference point: 0 = the beginning of the file (the default), 1 = the current position, 2 = the end of the file. So seek(0) goes back to the start.

For example, if a file holds the text roll_numbers = [1, 2, 3, 4, 5, 6], then after seek(10), read() starts at the 11th character, giving rs = [1, 2, 3, 4, 5, 6].

write and read move strings; seek and tell move the cursor.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.