Fred Agbo
October 23, 2026
HPYHr
GImage of the
moon.png image centered in the windowGImage(pix_array) and add the result to the
windowThe general approach for reading a text file is to first open the file and associate that file with a variable, commonly called its file handle
We will also use the with keyword to ensure that Python cleans up after itself (closes the file) when we are done with it.
with open(filename) as file_handle:
# Code to read the file using the file_handlePython gives you several ways to actually read in the data
read reads the entire file in as a
stringreadline or
readlines reads a single line or lines from
the fileread alongside
splitlines gets you a list of line
stringsThe read method reads the entire file
into a string, with includes newline characters
(\n) to mark the end of lines
Simple, but can be cumbersome to work with the newline characters, and, for large files, it can take a large amount of memory
As an example, the file:
One fish
two fish
red fish
blue fish
would get read as
"One fish\ntwo fish\nred fish\nblue fish"
Of the ways to read the file in a string at a time, using the file handler as an iterator and looping is probably best and certainly most flexible
Leads to code that looks like:
with open(filename) as f:
for line in f:
# Do something with the lineNote that most strategies preserve the newline character, which you very likely do not want, so be ready to strip them out before doing more processing
str.split() splits
str into a list of substrings at each
whitespace characterstr.split(separator) splits
str into a list of substrings at each
occurrence of separatorstr.splitlines() splits
str into a list of substrings at each line
breaksep.join(list) joins the elements of
list into a string, using
sep to separate themSo long as your files are not gigantic, using
read and then the
splitlines method can be a good
option
This does remove the newline characters, since it splits the string at them
with open(filename) as f:
lines = f.read().splitlines()
# Then you can do whatever you want with the list of linesYou can write text files using almost the same syntax as reading:
with open(filename, mode) as file_handle:
# Code to write the file using file_handleNote the mode parameter to
open here! Mode is a string which is
either
"w" to write a new file
(or overwrite an existing file)"a" to append new
contents to the end of an existing fileThe file handler supports the methods:
.write(some_string) to write a string to
the file.writelines(iterable_of_strings) to
write each iterable element to the fileIOErroropen encounters an error, it reports
the error by raising an exception with
IOError as its type.
tryPython uses the try statement to
indicate an interest in trying to handle a possible exception
In simplest form, the syntax is:
try:
# Code that may cause an exception
except type_of_exception:
# Code to handle that type of exceptiontype_of_exception here is the class
name of the exception being handled
IOError for the file reading errors we
are discussingAny exceptions arising from within the
try block or within functions
called within the try block would be “caught” and the lower
block of code run instead of terminating the program
As an example, the below function will repeatedly ask the user to supply a file name that actually exists.
It will not just immediately break should they give it an invalid filename!
def get_existing_file(prompt="Input a filename: "):
while True:
filename = input(prompt)
try:
with open(filename):
return filename
except IOError:
print("That filename is invalid!")If the open call succeeds, we
immediately just return the filename, but if it fails due to a
IOError, we display a message and then keep
asking
To the right are the contents of a text file named
PBride.txt. Which code snippet below would
print off the word “father”?
My name is Inigo Montoya.
You killed my father.
Prepare to die.
with open('PBride.txt') as f:
for line in f:
w = line.split()
if w[0] == "You":
print(w[-1])
c = read('PBride.txt')
print(c.find("father"))
with open('PBride.txt') as f:
c = f.read().splitlines()
print(c[1][4])
with open('PBride.txt') as f:
c = f.read()
i = c.find("f")
print(c[i:i+6])
Prob2.pymoby_dick.txt,
which contains the first paragraph from the classic text.word2piglatin
function
moby_bacon.txt