Text files
Opening, reading, writing and closing text files; file modes and offsets.
The essentials
Files store data permanently on secondary storage. A text file stores characters, organised in lines that end with the newline character '\n'. Python opens a file with open(filename, mode), which returns a file object. The file should be closed with close() after use, or opened using with open(...) as f:, which closes it automatically.
Key points
- 'r': read only; file must exist, otherwise FileNotFoundError. Pointer at the start. This is the default mode.
- 'w': write only; creates the file, or erases (truncates) an existing file. Pointer at the start.
- 'a': append; creates the file if needed; new data is written at the end.
- 'r+': read and write, file must exist. 'w+': write and read, old data erased. 'a+': append and read.
- read(): reads the whole file as one string; read(n) reads n characters.
- readline(): reads one line, including the '\n'.
- readlines(): reads all lines and returns a list of strings.
- write(s): writes string s and returns the number of characters written. f.write("Hello\n") returns 6.
- writelines(list): writes each string in a list; it does not add newlines automatically.
- tell(): returns the current position (offset) of the file pointer in bytes from the start.
- seek(offset, whence): moves the pointer; whence 0 = from start (default), 1 = from current position, 2 = from end. For text files, non-zero offsets from positions 1 and 2 are not allowed.
- Only strings can be written to a text file; numbers must be converted with str().
Common mistakes
- Opening an important file in 'w' mode when 'a' was meant; the old contents are lost.
- Forgetting that writelines() and write() do not add '\n' on their own.
Practice questions
Log in to answer these questions and see the explanations.Create free accountLog in