Lesson 14 of 2011 min read

Text File Handling in Python

Share:WhatsAppLinkedIn

Prerequisites: Strings, loops, functions, basic exception handling


1. What Are Files and Why File Handling?

  • A file is a named location on disk to store data permanently., Variables and data structures (lists, dicts) exist only in RAM, they are lost when the program ends., Files allow persistent storage - data survives after the program terminates., Python provides built-in functions to create, read, write, and manipulate files.

2. Text File vs Binary File

Feature Text File Binary File
Content Human-readable characters Encoded data (bytes)
Extension .txt, .csv, .html .dat, .bin, .pkl, .jpg
Line ending Translated (\n to OS-specific) Stored as-is
Read with Text editor Special programs
Example "Hello\n" stored as characters Pickled Python objects

3. Opening Files: open

Syntax

file_object = open(filename, mode)

File Modes

Mode Description File Pointer Creates File?
"r" Read only (default) Beginning No (error if missing)
"w" Write only Beginning Yes (overwrites existing)
"a" Append only End Yes (creates if missing)
"r+" Read and write Beginning No (error if missing)
"w+" Write and read Beginning Yes (overwrites existing)
"a+" Append and read End Yes (creates if missing)

Examples

# Open for reading (file must exist)
f = open("data.txt", "r")

# Open for writing (creates new / overwrites existing)
f = open("data.txt", "w")

# Open for appending (creates new if not exists)
f = open("data.txt", "a")

# Open for reading and writing
f = open("data.txt", "r+")

4. File Object Attributes

f = open("sample.txt", "r")

print(f.name) # Output: sample.txt
print(f.mode) # Output: r
print(f.closed) # Output: False

f.close
print(f.closed) # Output: True

5. Closing Files: close

Always close files after use to free system resources and flush data.

f = open("data.txt", "r")
content = f.read
f.close # IMPORTANT: Always close the file

6. The with Statement (Auto-Close)

The with statement automatically closes the file when the block ends, even if an exception occurs.

with open("data.txt", "r") as f:
 content = f.read
 print(content)
# File is automatically closed here - no need for f.close

print(f.closed) # Output: True

Best practice: Always use with for file handling.


7. Writing to Files

write, Writes a String

f = open("output.txt", "w")
f.write("Hello World\n")
f.write("Python is fun\n")
f.close

# File output.txt contains:
# Hello World
# Python is fun

Note: write does NOT add \n automatically. You must add it yourself.

write returns the number of characters written:

f = open("output.txt", "w")
count = f.write("Hello")
print(count) # Output: 5
f.close

writelines, Writes a List of Strings

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
f = open("output.txt", "w")
f.writelines(lines)
f.close

# File output.txt contains:
# Line 1
# Line 2
# Line 3

Note: writelines does NOT add \n between items, you must include them in the strings.


8. Reading from Files

Assume the file sample.txt contains:

Hello World
Python Programming
File Handling

read, Read Entire File

f = open("sample.txt", "r")
content = f.read
print(content)
f.close

# Output:
# Hello World
# Python Programming
# File Handling

read(n), Read n Characters

f = open("sample.txt", "r")
chunk = f.read(5)
print(chunk) # Output: Hello
print(f.read(6)) # Output: World (continues from position 5)
f.close

readline, Read One Line

f = open("sample.txt", "r")
line1 = f.readline
print(line1, end="") # Output: Hello World
line2 = f.readline
print(line2, end="") # Output: Python Programming
f.close

Note: readline includes the \n at the end of each line.

readline(n), Read n Characters from Current Line

f = open("sample.txt", "r")
part = f.readline(5)
print(part) # Output: Hello (reads 5 chars from first line)
f.close

readlines, Read All Lines into a List

f = open("sample.txt", "r")
lines = f.readlines
print(lines)
f.close

# Output: ['Hello World\n', 'Python Programming\n', 'File Handling\n']

Summary Table

Method Returns Reads
read str Entire file
read(n) str n characters
readline str One line
readline(n) str n characters from current line
readlines list All lines as list of strings

9. File Pointer: tell and seek

tell, Returns Current Position

f = open("sample.txt", "r")
print(f.tell) # Output: 0 (beginning of file)
f.read(5)
print(f.tell) # Output: 5
f.readline
print(f.tell) # Position after first line
f.close

seek(offset, reference), Move File Pointer

  • reference values:
  • 0 - beginning of file (default)
  • 1 - current position (only for binary files)
  • 2 - end of file (only for binary files)
f = open("sample.txt", "r")
f.read(10) # Read 10 characters
print(f.tell) # Output: 10

f.seek(0) # Go back to beginning
print(f.tell) # Output: 0
print(f.read(5)) # Output: Hello

f.seek(6) # Go to position 6
print(f.read(5)) # Output: World
f.close

10. Traversing a File with for Loop

# Most Pythonic way to read a file line by line
f = open("sample.txt", "r")
for line in f:
 print(line, end="")
f.close

# Output:
# Hello World
# Python Programming
# File Handling
# Using with statement (preferred)
with open("sample.txt", "r") as f:
 for line in f:
 print(line.strip) # strip removes \n

# Output:
# Hello World
# Python Programming
# File Handling

Practice Programs

Program 1: Create a File and Write Data

# Create a file and write user data
with open("students.txt", "w") as f:
 n = int(input("How many students? "))
 for i in range(n):
 name = input(f"Enter name of student {i+1}: ")
 f.write(name + "\n")

print("Data written successfully!")

# Test Run:
# How many students? 3
# Enter name of student 1: Aman
# Enter name of student 2: Priya
# Enter name of student 3: Rahul
# Data written successfully!

# File students.txt:
# Aman
# Priya
# Rahul

Program 2: Read Entire File

# Read and display entire file contents
with open("students.txt", "r") as f:
 content = f.read
 if content:
 print("File contents:")
 print(content)
 else:
 print("File is empty.")

# Output:
# File contents:
# Aman
# Priya
# Rahul

Program 3: Read Line by Line

# Read file line by line with line numbers
with open("students.txt", "r") as f:
 line_num = 0
 for line in f:
 line_num += 1
 print(f"Line {line_num}: {line.strip}")

# Output:
# Line 1: Aman
# Line 2: Priya
# Line 3: Rahul

Program 4: Read Words Separated by

# Create a file with #-separated words
with open("words.txt", "w") as f:
 f.write("apple#banana#cherry#date#elderberry")

# Read and display individual words
with open("words.txt", "r") as f:
 content = f.read
 words = content.split("#")
 print("Words in file:")
 for word in words:
 print(word)

# Output:
# Words in file:
# apple
# banana
# cherry
# date
# elderberry

Program 5: Count Vowels, Consonants, Uppercase, Lowercase

# Count vowels, consonants, uppercase and lowercase letters
with open("sample.txt", "r") as f:
 content = f.read

vowels = consonants = upper = lower = 0
vowel_set = "aeiouAEIOU"

for ch in content:
 if ch.isalpha:
 if ch in vowel_set:
 vowels += 1
 else:
 consonants += 1
 if ch.isupper:
 upper += 1
 else:
 lower += 1

print(f"Vowels : {vowels}")
print(f"Consonants : {consonants}")
print(f"Uppercase : {upper}")
print(f"Lowercase : {lower}")

# For sample.txt containing "Hello World\nPython Programming\nFile Handling\n"
# Output:
# Vowels : 11
# Consonants : 22
# Uppercase : 5
# Lowercase : 28

Program 6: Count Words and Lines

# Count words and lines in a file
with open("sample.txt", "r") as f:
 lines = f.readlines

line_count = len(lines)
word_count = 0

for line in lines:
 words = line.split
 word_count += len(words)

print(f"Number of lines: {line_count}")
print(f"Number of words: {word_count}")

# For sample.txt containing:
# Hello World
# Python Programming
# File Handling
# Output:
# Number of lines: 3
# Number of words: 6

Program 7: Remove Lines Containing a Specific Character

# Remove lines containing a specific character and write to new file
char = input("Enter character to remove lines containing it: ")

with open("sample.txt", "r") as fin:
 lines = fin.readlines

with open("filtered.txt", "w") as fout:
 count = 0
 for line in lines:
 if char not in line:
 fout.write(line)
 else:
 count += 1

print(f"Removed {count} line(s) containing '{char}'")
print("Remaining lines written to filtered.txt")

# If sample.txt contains:
# Hello World
# Python Programming
# File Handling
# Input: P
# Output:
# Removed 1 line(s) containing 'P'
# Remaining lines written to filtered.txt

# filtered.txt contains:
# Hello World
# File Handling

Program 8: Copy Content from One File to Another

# Copy content from source to destination file
source = input("Enter source filename: ")
destination = input("Enter destination filename: ")

try:
 with open(source, "r") as fin:
 content = fin.read

 with open(destination, "w") as fout:
 fout.write(content)

 print(f"Content copied from '{source}' to '{destination}' successfully!")
 print(f"Total characters copied: {len(content)}")

except FileNotFoundError:
 print(f"Error: File '{source}' not found!")

# Test Run:
# Enter source filename: sample.txt
# Enter destination filename: backup.txt
# Content copied from 'sample.txt' to 'backup.txt' successfully!
# Total characters copied: 45

Program 9: Display Words Starting with Uppercase

# Display all words that start with an uppercase letter
with open("sample.txt", "r") as f:
 content = f.read

words = content.split
upper_words = []

for word in words:
 if word[0].isupper:
 upper_words.append(word)

print("Words starting with uppercase:")
for word in upper_words:
 print(word)

# For sample.txt containing:
# Hello World
# Python Programming
# File Handling
# Output:
# Words starting with uppercase:
# Hello
# World
# Python
# Programming
# File
# Handling

Program 10: Search and Replace a Word in File

# Search and replace a word in a file
filename = "sample.txt"
old_word = input("Enter word to search: ")
new_word = input("Enter replacement word: ")

with open(filename, "r") as f:
 content = f.read

count = content.count(old_word)

if count > 0:
 new_content = content.replace(old_word, new_word)
 with open(filename, "w") as f:
 f.write(new_content)
 print(f"Replaced {count} occurrence(s) of '{old_word}' with '{new_word}'")
else:
 print(f"'{old_word}' not found in the file.")

# Test Run:
# Enter word to search: Python
# Enter replacement word: Java
# Replaced 1 occurrence(s) of 'Python' with 'Java'

Program 11: Count Occurrences of a Word

# Count occurrences of a specific word in a file
filename = "sample.txt"
search_word = input("Enter word to count: ").lower

with open(filename, "r") as f:
 content = f.read

words = content.lower.split
count = words.count(search_word)

print(f"The word '{search_word}' appears {count} time(s) in the file.")

# For sample.txt containing: "Hello World Hello Python Hello"
# Enter word to count: Hello
# The word 'hello' appears 3 time(s) in the file.

Program 12: Display Lines Containing a Specific Word

# Display all lines containing a specific word
filename = "sample.txt"
search_word = input("Enter word to search: ")

with open(filename, "r") as f:
 lines = f.readlines

found = False
print(f"Lines containing '{search_word}':")

for i, line in enumerate(lines, 1):
 if search_word in line:
 print(f" Line {i}: {line.strip}")
 found = True

if not found:
 print(f" '{search_word}' not found in any line.")

# For sample.txt containing:
# Hello World
# Python Programming
# File Handling in Python
# Enter word to search: Python
# Output:
# Lines containing 'Python':
# Line 2: Python Programming
# Line 3: File Handling in Python

Common Mistakes

Mistake Correct Approach
Forgetting to close the file Use with statement for auto-close
Opening a non-existent file in "r" mode Use try-except or check with os.path.exists
Forgetting \n in write write does not auto-add newline, add "\n" manually
Using readlines and forgetting \n in each item Use line.strip to remove trailing \n
Opening in "w" mode when you want to append "w" overwrites; use "a" to append
Not specifying end="" when printing lines readline includes \n, so print(line) adds a blank line
Confusing write and writelines write takes a string; writelines takes a list of strings

$1$2 Quick Tips

  1. File modes table is frequently asked, memorize r, w, a, r+, w+, a+.
  2. read vs readline vs readlines is a classic comparison question.
  3. Output prediction: Remember that readline includes \n and readlines returns a list with \n in each element.
  4. write returns the number of characters written, this is asked in MCQs.
  5. tell and seek are common 2-mark questions. Remember seek(0) goes to beginning.
  6. flush writes buffered data to file without closing it, sometimes asked.
  7. For coding questions, always use with statement, it shows good practice and earns marks.
  8. Common code-writing question: Count lines, words, or characters starting with a specific letter.

Test Your Knowledge

Take a quick quiz on this lesson

Start Quiz →

Prefer watching over reading?

Subscribe for free.

Subscribe on YouTube