Skip to content

Module 13 · File Handling — topic 9 of 15

Text files

Working with plain text: lines and line endings, splitting into lines and words, counting and searching, editing content by reading, transforming and writing back.

Beginner 8 min read·Lesson 202 of 306 in Python Programming

Learning objectives

  • Split text files into lines and words
  • Search and count within text files
  • Edit a text file safely

Definition

A text file stores characters organised into lines separated by newline characters. Processing text files usually means reading lines or words, transforming them with string methods, and writing results.

Introduction

Notes, logs, source code, subtitles — a huge amount of data is plain text. Python's string methods make text files easy to process.

Why it matters

Text processing combines file handling with everything you know about strings, and it appears in countless scripts and automation tasks.

Detailed explanation

In text mode, Python converts any of \n, \r\n and \r to \n when reading ('universal newlines'), so your code only deals with \n.

text.splitlines() splits into lines without the line endings and keeps empty lines; text.split() splits into words on any whitespace.

Searching: use the in operator, str.find, str.startswith, or the re module for patterns.

Counting: len(lines), len(words), collections.Counter for word frequencies.

Text files can't be edited in place like a document. To change one, read the content, modify it in memory, and write the whole content back.

For very large files, process line by line and write the changes to a new file instead of holding everything in memory.

Normalising text — lower-casing, stripping punctuation — makes counting and searching more accurate.

Syntax

Python
with open(path, encoding="utf-8") as f:
text = f.read()
lines = text.splitlines()
words = text.split()
new_text = text.replace("old", "new")
with open(path, "w", encoding="utf-8") as f:
f.write(new_text)
  • splitlines() for lines.
  • split() for words.
  • Edit by read → modify → write.

Code examples

Lines including empty ones

Python
with open("t.txt", "w", encoding="utf-8") as f:
f.write("line one\nline two\n\nline four")
with open("t.txt", encoding="utf-8") as f:
lines = f.read().splitlines()
print(len(lines), lines)
Output
4 ['line one', 'line two', '', 'line four']

Word counts

Python
from collections import Counter
with open("w.txt", "w", encoding="utf-8") as f:
f.write("the quick brown fox jumps over the lazy dog the end\n")
with open("w.txt", encoding="utf-8") as f:
words = f.read().split()
print(len(words), Counter(words).most_common(1))
Output
11 [('the', 3)]

More examples

Search and replace in a file

Python
import re
content = "Python is fun.\nI write python daily.\nJava is fine too.\n"
with open("notes.txt", "w", encoding="utf-8") as f:
f.write(content)
with open("notes.txt", encoding="utf-8") as f:
matches = [(i, line.rstrip("\n")) for i, line in enumerate(f, 1) if "python" in line.lower()]
print(matches)
with open("notes.txt", encoding="utf-8") as f:
text = f.read()
with open("notes.txt", "w", encoding="utf-8") as f:
f.write(re.sub(r"python", "Python", text, flags=re.IGNORECASE))
with open("notes.txt", encoding="utf-8") as f:
print(f.read().splitlines()[1])
Output
[(1, 'Python is fun.'), (2, 'I write python daily.')]
I write Python daily.

Step-by-step explanation

  • The search reports line numbers using enumerate starting at 1.
  • The replacement reads the whole file, fixes the capitalisation with a case-insensitive regex, and writes it back.
  • Reading again confirms the second line changed.

Expected output

Running “Search and replace in a file” prints exactly:

TextOutput
[(1, 'Python is fun.'), (2, 'I write python daily.')]
I write Python daily.

Practical applications

  • Bulk-renaming terms in documentation.
  • Extracting lines that match a pattern from logs.

Best practices

  • Read fully, then write, when editing a file.
  • Normalise case before counting words.
  • Process big files line by line.

Common mistakes

Opening for writing before reading

Avoid

with open(p, "w") as out, open(p) as src:
out.write(src.read().upper())

Prefer

with open(p, encoding="utf-8") as f:
text = f.read()
with open(p, "w", encoding="utf-8") as f:
f.write(text.upper())

"w" empties the file before it is read.

Important notes

  • For safety, write edits to a new file and replace the original with os.replace.

Key takeaways

  • splitlines() and split() break text into lines and words.
  • Text files are edited by reading, changing and rewriting.
  • Python normalises line endings to \n.

Try it yourself

  1. 1
    Print the five most common words in a text file, ignoring case and punctuation.
  2. 2
    Remove all blank lines from a file.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions cover the “File Handling” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhich mode creates a new file but fails if the file already exists?
Practise this module