Text File Practice Programs
Board questions on text files are the same handful of programs, dressed differently — count something, find something, copy something, remove something. Here are ten of them, written the way the paper asks: as a function with a name, doing one job.
1The file every program reads
All ten programs run on the same five-line file, story.txt. Every output on this page was produced by running the program against it.
India is a land of many festivals.
The lights of Diwali are famous.
A festival brings the people together.
Every state has its own colours.
People travel home to celebrate them.0, walk the file with for line in f, test the thing being asked about, close the file, print the answer. Nine of the ten below are that skeleton with a different if in the middle.2Program 1 — count the lines beginning with ‘A’
Write a function to count the number of lines in story.txt that begin with the letter ‘A’ or ‘a’.
def count_a_lines():
f = open('story.txt', 'r')
count = 0
for line in f:
if line[0] == 'A' or line[0] == 'a':
count = count + 1
f.close()
print('Lines beginning with A:', count)
count_a_lines()Lines beginning with A: 1
for line in f:One line at a time. The line still carries its \n, which does not matter here.
line[0]The first character of the line. This is the only part the question is about.
== 'A' or line[0] == 'a'Both cases, because the question says the letter A, not the capital A. line[0] in 'Aa' says the same thing more briefly.
for line in f is safe: a blank line in the file arrives as '\n', which has a character 0. But splitting the text yourself with data.split('\n') produces genuinely empty strings — one for each blank line, and one at the end — and line[0] on those raises IndexError: string index out of range. line.startswith('A') is safe on every string, empty ones included.3Program 2 — count vowels, consonants, uppercase and lowercase
Write a function to count the vowels, consonants, uppercase letters and lowercase letters in story.txt.
def count_letters():
f = open('story.txt', 'r')
data = f.read()
f.close()
vowels = 0
consonants = 0
uppercase = 0
lowercase = 0
for ch in data:
if ch.isalpha():
if ch in 'AEIOUaeiou':
vowels = vowels + 1
else:
consonants = consonants + 1
if ch.isupper():
uppercase = uppercase + 1
else:
lowercase = lowercase + 1
print('Vowels:', vowels)
print('Consonants:', consonants)
print('Uppercase letters:', uppercase)
print('Lowercase letters:', lowercase)
count_letters()Vowels: 57 Consonants: 85 Uppercase letters: 6 Lowercase letters: 136
ch.isalpha() throws them out, and everything inside that if is then about a real letter. Notice both questions are asked about the same character: vowel-or-consonant, and upper-or-lower.4Program 3 — count the words longer than four characters
Write a function to count the words in story.txt that have more than four characters.
def long_words():
f = open('story.txt', 'r')
count = 0
for line in f:
for word in line.split():
if len(word) > 4:
count = count + 1
f.close()
print('Words longer than 4 characters:', count)
long_words()Words longer than 4 characters: 16
line.split() breaks the line at every run of blank space and drops the empty pieces, so it works even where two spaces crept in. The full stop stays attached to the last word, which makes festivals. ten characters — add .strip('.,') if the question means the word alone.5Program 4 — display the lines shorter than 35 characters
Write a function to display every line of story.txt that is fewer than 35 characters long.
def short_lines():
f = open('story.txt', 'r')
for line in f:
if len(line.strip()) < 35:
print(line.strip())
f.close()
short_lines()India is a land of many festivals. The lights of Diwali are famous. Every state has its own colours.
\n counts as a character and every line measures one longer than it looks. On a question with a boundary like “fewer than 35”, that single character is the difference between the right answer and the wrong one.6Program 5 — copy the lines containing a word into another file
Write a function that copies every line of story.txt containing the word India into a new file india.txt, and reports how many were copied.
def copy_matching(word):
source = open('story.txt', 'r')
target = open('india.txt', 'w')
count = 0
for line in source:
if word in line:
target.write(line)
count = count + 1
source.close()
target.close()
print('Lines copied:', count)
copy_matching('India')
print(open('india.txt').read())Lines copied: 1 India is a land of many festivals.
target = open('india.txt', 'w')Both files are open at once — one to read from, one to write to. 'w' creates india.txt if it is not there, and empties it if it is.
if word in line:Membership on a string: does this line contain that text anywhere? This is a substring test, so 'India' would also match 'Indian'.
target.write(line)The line still has its \n on the end, so the copy comes out with proper lines. Nothing needs adding.
7Program 6 — display the file with line numbers
Write a function to display the contents of story.txt with each line numbered from 1.
def numbered():
f = open('story.txt', 'r')
number = 1
for line in f:
print(number, line.strip())
number = number + 1
f.close()
numbered()1 India is a land of many festivals. 2 The lights of Diwali are famous. 3 A festival brings the people together. 4 Every state has its own colours. 5 People travel home to celebrate them.
8Program 7 — find the longest line
Write a function to find and display the longest line in story.txt, along with its length.
def longest_line():
f = open('story.txt', 'r')
longest = ''
for line in f:
line = line.strip()
if len(line) > len(longest):
longest = line
f.close()
print('The longest line is:')
print(longest)
print('Its length is', len(longest))
longest_line()The longest line is: A festival brings the people together. Its length is 38
n > biggest to len(line) > len(longest).9Program 8 — count how many times a word appears
Write a function that counts how many times a given word appears in story.txt, ignoring capitals and punctuation.
def count_word(word):
f = open('story.txt', 'r')
count = 0
for line in f:
for w in line.split():
if w.strip('.,').lower() == word.lower():
count = count + 1
f.close()
print(word, 'appears', count, 'times')
count_word('the')
count_word('festival')the appears 2 times festival appears 1 times
count() would find the inside together and them and answer 3. When the question says word, split into words and compare whole words — and .lower() on both sides so that The counts too.10Program 9 — write records, then read them back
Write one function that stores names and marks in result.txt, one record per line, and another that displays the students who scored 75 or more.
def create_file():
names = ['Ravi', 'Meera', 'Amit']
marks = [78, 91, 65]
f = open('result.txt', 'w')
for i in range(len(names)):
f.write(names[i] + ',' + str(marks[i]) + '\n')
f.close()
def show_toppers():
f = open('result.txt', 'r')
for line in f:
name, mark = line.strip().split(',')
if int(mark) >= 75:
print(name, 'scored', mark)
f.close()
create_file()
show_toppers()Ravi scored 78 Meera scored 91
f.write(names[i] + ',' + str(marks[i]) + '\n')A record is a line you build yourself. str() is needed because write() refuses a number, and the \n is needed because write() adds nothing.
line.strip().split(',')strip() first, or the mark would arrive as '78\n'. split(',') then gives a two-item list, which the two names on the left unpack.
int(mark)Everything read from a text file is a string. '91' > '9' is False, so comparing without int() gives silently wrong answers.
11Program 10 — remove every line containing a word
Write a function that removes from story.txt every line containing a given word, and reports how many were removed.
import os
def remove_lines(word):
source = open('story.txt', 'r')
temp = open('temp.txt', 'w')
removed = 0
for line in source:
if word in line:
removed = removed + 1
else:
temp.write(line)
source.close()
temp.close()
os.remove('story.txt')
os.rename('temp.txt', 'story.txt')
print('Lines removed:', removed)
remove_lines('Diwali')
print(open('story.txt').read())Lines removed: 1 India is a land of many festivals. A festival brings the people together. Every state has its own colours. People travel home to celebrate them.
story.txt in 'w' instead would empty it at once, and a crash halfway through would take the lot.12Run one yourself
The file is here in the browser. Change the program to answer a different question — lines ending in a full stop, words starting with a capital, characters excluding spaces:
13The five patterns behind all ten
count = 0 … if …: count = count + 1Programs 1, 3, 8, 10. The only thing that changes is the test.
for ch in data:Program 2. read() the file into one string first, then walk the characters.
if …: print(line.strip())Programs 4 and 6. No counter at all — the answer is the printing.
source = open(…, 'r'); target = open(…, 'w')Programs 5 and 10. One is read, one is written, and both get closed.
if len(line) > len(longest): longest = lineProgram 7. Hold the best so far, replace it when something beats it.
- 1
Count the lines that end with a full stop.
Hint · line.strip() first, then line.endswith('.').
- 2
Count the characters in the file, not counting spaces.
Hint · Walk the characters and skip the ones where ch == ' '.
- 3
Display every word that starts with a capital letter, one per line.
Hint · word[0].isupper() — and split() the line first.
- 4
Copy
story.txtintocopy.txtwith the lines in reverse order.Hint · readlines() gives a list, and lists have reverse().
- 5
Ask the user for a word and replace every occurrence of it in the file with
****.Hint · read(), replace(), write it back in mode 'w'.
Why does a line-length program call line.strip() before len()?
A program reads '78' from a file and compares it with 75. What must it do first?
Which counts the WORD 'the' correctly?
Reading with for line in f, a blank line in the file comes back as...