VM-LEARNING /class.xii ·track.cs ·ch-1-5 session: 2026_27
$cd ..

~/Text Files

root@vm-learning ~ $ open ch-1-5
UNIT 1 ▪ CHAPTER 5
05
Text Files
write · writelines · read · readline · readlines · seek · tell · Worked Programs
A text file stores ordinary characters — letters, digits, punctuation, whitespace — that any editor (Notepad, VS Code) can display. In Python, every read from a text file gives you a string (str); every write sends a string back to disk.
Real-life analogy. A text file is like a printed book. You can open it at page 1 and read line by line, you can flip to any page you like, or you can turn to the last page and add a new paragraph. Python’s 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:

5.1.1 Text-file modes — one-glance table

ModeFile must exist?PositionRead?Write?Truncates?
"r"YesStart
"w"No (creates)Start⚠ Yes
"a"No (creates)EndNo
"x"Must not existStart
"r+"YesStartNo
"w+"No (creates)Start⚠ Yes
"a+"No (creates)EndNo

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.

with open("marks.txt", "w") as f: n = f.write("Asha 92\n") # writes 8 characters, returns 8 f.write("Rahul 78\n") f.write("Riya 85\n") print("First line wrote", n, "characters.")
Mnemonic — “write() writes exactly what you give it.” No extra newline, no extra space between arguments, no magic formatting.

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.

lines = ["Asha 92\n", "Rahul 78\n", "Riya 85\n"] with open("marks.txt", "w") as f: f.writelines(lines)
Despite its name, 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.

marks = 85 with open("marks.txt", "w") as f: # f.write(marks) # ❌ TypeError: write() requires str f.write(str(marks) + "\n") # ✅ "85\n" f.write(f"Total = {marks}\n") # ✅ f-string, most readable

5.2.4 "w" versus "a" — in action

with open("log.txt", "w") as f: # wipes old file f.write("Line 1\n") with open("log.txt", "a") as f: # keeps Line 1, adds more f.write("Line 2\n") f.write("Line 3\n") with open("log.txt", "r") as f: print(f.read())
Line 1 Line 2 Line 3

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.

Imagine the file contains exactly:
Asha 92 Rahul 78 Riya 85
The four read methods below operate on this same file. Notice the difference in the shape of the return value.

5.3.1 read() — entire file as one string

with open("marks.txt", "r") as f: content = f.read() print(type(content), len(content)) print(content)
<class 'str'> 24 Asha 92 Rahul 78 Riya 85

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.

with open("marks.txt", "r") as f: first8 = f.read(8) # first 8 characters next10 = f.read(10) # next 10 characters print(repr(first8)) print(repr(next10))
'Asha 92\nR' 'ahul 78\nRi'

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.

with open("marks.txt", "r") as f: print(repr(f.readline())) # 'Asha 92\n' print(repr(f.readline())) # 'Rahul 78\n' print(repr(f.readline())) # 'Riya 85\n' print(repr(f.readline())) # '' (EOF)
Use line.rstrip("\n") or line.strip() when you want the line without the trailing newline.

5.3.4 readlines() — every line as a list

with open("marks.txt", "r") as f: rows = f.readlines() print(rows)
['Asha 92\n', 'Rahul 78\n', 'Riya 85\n']

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.

with open("marks.txt", "r") as f: for line in f: # one line per iteration print(line.rstrip()) # strip the trailing newline
Asha 92 Rahul 78 Riya 85
This is the preferred way to process a file line by line: short, memory-efficient, works on files of any size.

5.3.6 Side-by-side comparison

MethodReturnsMemoryBest for
read()str — whole fileO(file size)Small files
read(n)str — up to n charsO(n)Chunked reading
readline()str — one lineO(line)Manual line-by-line
readlines()list[str]O(file size)When you need random access to lines
for line in fEach line in turnO(line)Processing any file — recommended

5.4 The File Pointer — tell() and seek()

Every open file has an invisible file pointer — a marker that remembers where the next read or write will take place. It starts at byte 0 (or at the end for append mode) and moves forward automatically as you read or write.

5.4.1 f.tell() — where is the pointer now?

with open("marks.txt", "r") as f: print(f.tell()) # 0 — at the start f.read(4) # read 'Asha' print(f.tell()) # 4 — moved 4 bytes forward f.readline() # read to end of line print(f.tell()) # 8 — after '\n'

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.

whenceMeaningWhere offset is measured from
0 (default)os.SEEK_SETStart of the file
1os.SEEK_CURCurrent position
2os.SEEK_ENDEnd of the file
In text mode (the default), only 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).
with open("marks.txt", "r") as f: f.read(4) # pointer now at 4 f.seek(0) # back to the beginning print(f.readline()) # 'Asha 92'

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.

Problems with extra blank lines (\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.

import datetime with open("visitor_log.txt", "a") as f: f.write(f"{datetime.datetime.now()} visit\n")

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

with open("student.txt", "w") as f: f.write(input("Name : ") + "\n") f.write(input("Marks: ") + "\n") print("Saved to student.txt")

5.7.2 Count the total number of lines, words and characters in a file

lines = words = chars = 0 with open("story.txt", "r") as f: for line in f: lines += 1 words += len(line.split()) chars += len(line) print("Lines :", lines) print("Words :", words) print("Characters:", chars)

5.7.3 Count vowels in a file

vowels = "aeiouAEIOU" count = 0 with open("story.txt", "r") as f: for ch in f.read(): if ch in vowels: count += 1 print("Vowels:", count)

5.7.4 Count lines starting with a particular letter

letter = "T" n = 0 with open("story.txt", "r") as f: for line in f: if line.startswith(letter): n += 1 print(f"Lines beginning with '{letter}': {n}")

5.7.5 Copy one text file into another

with open("story.txt", "r") as src, open("copy.txt", "w") as dst: dst.write(src.read()) print("Copied.")

5.7.6 Display only the lines containing a keyword

keyword = input("Search word: ").lower() with open("story.txt", "r") as f: for line in f: if keyword in line.lower(): print(line.rstrip())

5.7.7 Word-frequency counter

freq = {} with open("story.txt", "r") as f: for line in f: for w in line.lower().split(): w = w.strip(".,!?;:'\"()") if w: freq[w] = freq.get(w, 0) + 1 # top 5 most frequent words top = sorted(freq.items(), key=lambda x: x[1], reverse=True)[:5] for word, count in top: print(f"{word:<15} {count}")

5.7.8 Replace every occurrence of one word with another

old, new = "Delhi", "Mumbai" with open("article.txt", "r") as f: text = f.read() text = text.replace(old, new) with open("article.txt", "w") as f: f.write(text) print(f"Replaced '{old}' with '{new}'.")
Pattern — read-modify-write. Text files cannot be edited in place. Read the whole file, transform the string, then write it back in "w" mode. For huge files, write to a new file and rename afterwards.

5.7.9 Count upper-case, lower-case, digits & spaces

u = l = d = sp = other = 0 with open("story.txt", "r") as f: for ch in f.read(): if ch.isupper(): u += 1 elif ch.islower(): l += 1 elif ch.isdigit(): d += 1 elif ch.isspace(): sp += 1 else: other += 1 print(f"U={u} L={l} D={d} spaces={sp} other={other}")

5.7.10 Longest line in the file

longest = "" with open("story.txt", "r") as f: for line in f: line = line.rstrip("\n") if len(line) > len(longest): longest = line print("Longest line:", longest) print("Length :", len(longest))

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.

def show_file(path): try: with open(path, "r", encoding="utf-8") as f: for i, line in enumerate(f, 1): print(f"{i:3}: {line.rstrip()}") except FileNotFoundError: print("File", path, "does not exist.") except PermissionError: print("Not allowed to read", path) show_file("marks.txt")

5.9 Common Mistakes to Avoid

#MistakeFix
1Forgetting \n with write()Always end lines with "\n"
2Passing an int or float to write()Convert first — f.write(str(n))
3Expecting writelines() to add newlinesInclude \n in each string yourself
4Using "w" to add data — old content wipedUse "a" (append)
5Reading a file twice without seek(0)Second read() returns "" — pointer is at the end
6Loading a huge file with readlines()Use for line in f: instead
7Leaving \n on each line from readline()Use line.rstrip() before processing / printing
8Opening without with and forgetting close()Use with open(…) as f:

Quick-revision summary

  • Three writing methods: write(s), writelines(list). Neither adds newlines — include \n yourself.
  • Five reading strategies: read(), read(n), readline(), readlines(), and the preferred for line in f.
  • Each read() / write() advances the file pointer. Use tell() to see it, seek() to move it.
  • Text mode returns str; you must convert numbers with str() 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 with and handle FileNotFoundError.
🧠Practice Quiz — test yourself on this chapter