Board Formulas
🐍 PythonπŸ“… Day 17

Text File Handling in Python

Open, write, read and append text files in Python, close them safely with with, and move around a file using seek() and tell().

🎯

Learning objectives

  • β†’Choose the right file mode: r, w, a, r+, w+ or a+
  • β†’Write with write() and writelines(); read with read(), readline() and readlines()
  • β†’Use with so that files are always closed
  • β†’Process a file line by line and use seek() and tell() to move the file pointer

πŸ’‘ Key points

  • open(name, mode) returns a file object. Close it with close(), or better, use a with block that closes it for you.
  • 'r' reads (the file must exist), 'w' writes (creates the file or ERASES the old content), 'a' appends to the end.
  • Adding + allows both reading and writing: r+ does not erase the file, w+ erases it first, a+ writes only at the end.
  • read() returns the whole file as one string, readline() returns the next line, readlines() returns a list of all lines.
  • write() takes one string and writelines() takes a list of strings; neither adds newlines for you.
  • Each line you read (except perhaps the last) still has its newline character at the end; strip() it before comparing or printing.
  • tell() gives the current position in the file; seek(n) moves to position n, and seek(0) goes back to the start.

πŸ’» Code examples(6)

#1Writing a file with write()
python
f = open("poem.txt", "w")
f.write("Twinkle twinkle little star\n")
f.write("How I wonder what you are\n")
f.write("Up above the world so high\n")
f.close()
print("Saved poem.txt")
Output
Saved poem.txt
'w' creates poem.txt in the folder your program runs from. Each \n ends a line; without it, everything would be on one line.
#2Three ways to read
python
with open("poem.txt", "r") as f:
    print(f.readline(), end="")  # one line
    print(f.readline().strip())  # remove the \n
    rest = f.readlines()         # remaining lines
print(rest)

with open("poem.txt") as f:      # "r" is default
    text = f.read()              # whole file
print(len(text), "characters")
Output
Twinkle twinkle little star
How I wonder what you are
['Up above the world so high\n']
81 characters
Each read continues from where the last one stopped. The with block closes the file automatically, even if an error happens inside it.
#3Appending and writelines()
python
more = ["Like a diamond in the sky\n",
        "Twinkle twinkle little star\n"]
with open("poem.txt", "a") as f:
    f.writelines(more)

with open("poem.txt") as f:
    for n, line in enumerate(f, start=1):
        print(n, line.rstrip())
Output
1 Twinkle twinkle little star
2 How I wonder what you are
3 Up above the world so high
4 Like a diamond in the sky
5 Twinkle twinkle little star
'a' keeps the old lines and adds new ones at the end. Looping over the file object gives one line at a time, which works even for huge files.
#4Counting lines, words and lines starting with T
python
lines = words = t_lines = 0
with open("poem.txt") as f:
    for line in f:
        lines += 1
        words += len(line.split())
        if line.startswith("T"):
            t_lines += 1
print("Lines:", lines)
print("Words:", words)
print("Lines starting with T:", t_lines)
Output
Lines: 5
Words: 26
Lines starting with T: 2
This read-loop-count pattern answers most questions about a text file: counting words, vowels, a particular word, or lines that match a condition.
#5seek() and tell()
python
with open("poem.txt") as f:
    print(f.tell())          # 0: at the start
    print(f.read(7))         # read 7 characters
    print(f.tell())          # now at 7
    f.seek(8)                # jump to position 8
    print(f.read(7))
    f.seek(0)                # back to the start
    print(f.readline().strip())
Output
0
Twinkle
7
twinkle
Twinkle twinkle little star
read(n) reads n characters. The position counts bytes; on Windows each line ending takes 2 bytes, so positions after the first line differ there.
#6Copying selected lines to another file
python
with open("poem.txt") as src:
    lines = src.readlines()

with open("other.txt", "w") as dst:
    for line in lines:
        if not line.startswith("T"):
            dst.write(line)

with open("other.txt") as f:
    print(f.read(), end="")
Output
How I wonder what you are
Up above the world so high
Like a diamond in the sky
Read from one file, filter, write to another. Opening other.txt with 'w' means running the program twice does not duplicate lines.

🎯 Practice

Q1. Which mode adds new lines to the end of an existing file without erasing it?+

'a' (append), or 'a+' if you also want to read.

Q2. What is the difference between read(), readline() and readlines()?+

read() returns the whole file as one string. readline() returns just the next line. readlines() returns a list containing every line.

Q3. Write a program that counts the lines in story.txt that start with 'A'.+

count = 0 with open('story.txt') as f: for line in f: if line.startswith('A'): count += 1 print(count)

Q4. What happens if you open a file that does not exist in 'r' mode? In 'w' mode?+

'r' raises FileNotFoundError. 'w' creates a new empty file.

Q5. What does f.seek(0) do?+

It moves the file pointer back to the beginning, so the next read starts from the first character again.

πŸ“ Notes

File modes in one place

  • "r" read only. File must exist. Pointer at the start. This is the default.
  • "w" write only. Creates the file, or erases it if it exists.
  • "a" append only. Creates the file if needed; every write goes to the end.
  • "r+" read and write. File must exist; nothing is erased, but the pointer starts at the beginning, so a write overwrites the text there.
  • "w+" read and write. Creates the file, or erases it first.
  • "a+" read and append. Creates the file if needed; the pointer starts at the end, so seek(0) before reading. Writes always go to the end.

Why with is better than close()

If an error happens between open() and close(), the close() line never runs, and data you wrote may not be saved. A with block always closes the file when the block ends:

with open("log.txt", "a") as f:
    f.write("Logged in\n")
# file is closed here

Paths

A plain name like "poem.txt" means the folder your program runs from. You can also give a full path. On Windows, use a raw string so backslashes are not treated as escape sequences:

f = open(r"C:\school\marks.txt")

Handling a missing file

Combine today's topic with Day 16:

try:
    with open("marks.txt") as f:
        print(f.read())
except FileNotFoundError:
    print("marks.txt not found")

Common mistakes

  • Opening with "w" by accident: the old contents are gone immediately.
  • Forgetting \n in write(): all lines run together.
  • Comparing lines without strip(): line == "Amit" is False when the line is really "Amit\n".
  • Writing numbers: f.write(95) raises TypeError. Write str(95) or use an f-string.
  • Reading twice: after read(), the pointer is at the end, so a second read() returns "". Use seek(0) first.

Next: Day 18 β€” Binary and CSV Files, for storing whole Python objects and spreadsheet-style data.