str); every write sends a string back to disk.
read, readline, readlines, seek and write are just the tools for doing exactly those actions.
5.1 Text Files — A Quick Recap
From Chapter 4 you already know:
- Text mode is the default of
open();"r"="rt","w"="wt","a"="at". - Always prefer
with open(…) as f:so the file closes automatically. - A text file ends each line with the newline character
\n.
5.1.1 Text-file modes — one-glance table
| Mode | File must exist? | Position | Read? | Write? | Truncates? |
|---|---|---|---|---|---|
"r" | Yes | Start | ✅ | ❌ | — |
"w" | No (creates) | Start | ❌ | ✅ | ⚠ Yes |
"a" | No (creates) | End | ❌ | ✅ | No |
"x" | Must not exist | Start | ❌ | ✅ | — |
"r+" | Yes | Start | ✅ | ✅ | No |
"w+" | No (creates) | Start | ✅ | ✅ | ⚠ Yes |
"a+" | No (creates) | End | ✅ | ✅ | No |
5.2 Writing to a Text File
5.2.1 write(s) — write one string
write() sends the string to the file and returns the number of characters written. It does not add a newline automatically — you must include \n yourself when you want one.
5.2.2 writelines(list_of_strings) — write many strings at once
writelines() accepts any iterable of strings and writes each one in order. It, too, does not add newlines.
writelines() does not write “one line per item.” If your strings don’t end with \n, everything merges onto one line.
5.2.3 Writing numbers — you must convert to str first
Text files store only characters. If you pass a plain int or float, Python raises TypeError. Use str() or an f-string.
5.2.4 "w" versus "a" — in action
5.3 Reading from a Text File
Python offers four ways to read a text file. Each gives you the data in a different shape.
5.3.1 read() — entire file as one string
Internally the newline characters are still there — they just don’t look special when printed.
5.3.2 read(n) — read at most n characters
Handy when the file is huge and you don’t want to load it all at once.
5.3.3 readline() — one line at a time
Returns the next line including the trailing \n. Returns an empty string "" when there is nothing more to read.
line.rstrip("\n") or line.strip() when you want the line without the trailing newline.
5.3.4 readlines() — every line as a list
Each string keeps its trailing \n. readlines() loads the whole file into memory — avoid it on very large files.
5.3.5 Iterating over the file object directly (most Pythonic)
A file object is its own iterator — looping over it gives one line at a time without loading the whole file.
5.3.6 Side-by-side comparison
| Method | Returns | Memory | Best for |
|---|---|---|---|
read() | str — whole file | O(file size) | Small files |
read(n) | str — up to n chars | O(n) | Chunked reading |
readline() | str — one line | O(line) | Manual line-by-line |
readlines() | list[str] | O(file size) | When you need random access to lines |
for line in f | Each line in turn | O(line) | Processing any file — recommended |
5.4 The File Pointer — tell() and seek()
5.4.1 f.tell() — where is the pointer now?
5.4.2 f.seek(offset, whence=0) — jump to a new position
seek moves the pointer so the next read starts from a chosen position.
whence | Meaning | Where offset is measured from |
|---|---|---|
0 (default) | os.SEEK_SET | Start of the file |
1 | os.SEEK_CUR | Current position |
2 | os.SEEK_END | End of the file |
seek(0) or a position previously returned by tell() is guaranteed to work. Use whence=1 / whence=2 in binary mode (covered in Chapter 6).
5.5 Line Endings — the \n Character
Python uses \n (LF) as its single “newline” character in text mode. If you’re on Windows, the operating system actually stores \r\n (CR + LF) on disk — but Python transparently translates between the two for you. You don’t have to worry about it if you keep the file open in text mode.
\r\r\n) usually mean the file was opened in binary mode when it should have been text, or vice-versa. Stick to text mode for text files and this cannot happen.
5.6 Appending to a Text File
Append mode ("a") is perfect for logs, chat histories, and any file that grows over time.
Run the program three times and open the log — three time-stamped lines, not one.
5.7 CBSE-style Worked Programs
5.7.1 Write the user’s name and marks to a file
5.7.2 Count the total number of lines, words and characters in a file
5.7.3 Count vowels in a file
5.7.4 Count lines starting with a particular letter
5.7.5 Copy one text file into another
5.7.6 Display only the lines containing a keyword
5.7.7 Word-frequency counter
5.7.8 Replace every occurrence of one word with another
"w" mode. For huge files, write to a new file and rename afterwards.
5.7.9 Count upper-case, lower-case, digits & spaces
5.7.10 Longest line in the file
5.8 Bringing it all together — safe file handling
Real exam programs should combine everything you have learned: with, appropriate mode, try/except, and clear output.
5.9 Common Mistakes to Avoid
| # | Mistake | Fix |
|---|---|---|
| 1 | Forgetting \n with write() | Always end lines with "\n" |
| 2 | Passing an int or float to write() | Convert first — f.write(str(n)) |
| 3 | Expecting writelines() to add newlines | Include \n in each string yourself |
| 4 | Using "w" to add data — old content wiped | Use "a" (append) |
| 5 | Reading a file twice without seek(0) | Second read() returns "" — pointer is at the end |
| 6 | Loading a huge file with readlines() | Use for line in f: instead |
| 7 | Leaving \n on each line from readline() | Use line.rstrip() before processing / printing |
| 8 | Opening without with and forgetting close() | Use with open(…) as f: |
Quick-revision summary
- Three writing methods:
write(s),writelines(list). Neither adds newlines — include\nyourself. - Five reading strategies:
read(),read(n),readline(),readlines(), and the preferredfor line in f. - Each
read()/write()advances the file pointer. Usetell()to see it,seek()to move it. - Text mode returns
str; you must convert numbers withstr()before writing. - Append (
"a") keeps existing data; write ("w") wipes it; read ("r") only reads. - Read-modify-write pattern: text files cannot be edited in place.
- Wrap every file operation in
withand handleFileNotFoundError.