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.
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
- splitlines() for lines.
- split() for words.
- Edit by read → modify → write.
Code examples
Lines including empty ones
4 ['line one', 'line two', '', 'line four']
Word counts
11 [('the', 3)]More examples
Search and replace in a file
[(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:
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
Prefer
"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
- 1Print the five most common words in a text file, ignoring case and punctuation.
- 2Remove 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?