Reading Text Files
A text file stores characters that a program can read later. In these exercises, the supplied files use UTF-8 encoding. A relative filename is resolved from the program's current working directory; it is not an internet address.
Read a complete file
with open("sample.txt", "r", encoding="utf-8") as source:
text = source.read()
print(text)
"r" opens an existing file for reading. read() returns one string, including spaces and line breaks. with closes the file when the indented block finishes. The variable text remains available after the block. Reading does not change the file.
An empty file gives an empty string. A missing filename raises FileNotFoundError; use the provided filenames for these exercises. You do not need error handling yet.
Read one line at a time
Loop over the open file to process its lines in order. Use strip() to remove the newline and surrounding whitespace; lower() makes comparisons case-insensitive.
with open("words.txt", "r", encoding="utf-8") as source:
for line in source:
word = line.strip().lower()
if word:
print(word)
This skips blank lines. A wordlist can also contain comments or other entries to ignore. Most Vowels and Palindrome Discovery supply a helper that returns a lowercase word for a line containing only letters A–Z, or an empty string for any other line.
Read numeric measurements
If each line contains one whole number, read the lines in order and convert each with int().
values = []
with open("measurements.txt", "r", encoding="utf-8") as source:
for line in source:
values.append(int(line))
print(values)
Each line is text and usually ends with a newline. int() accepts surrounding whitespace, including that newline. For this example, every line contains a valid integer and there are no blank lines. A blank or nonnumeric line would raise ValueError.
Keep loading separate from calculation
A loader reads a file and returns text or numbers. A calculation function receives those values as arguments. This lets you test a calculation with a tiny list or string without creating a file for every experiment.
Before Run, check that the named fixture is available in the exercise workspace. Follow the exercise's file instructions; your computer's personal files are not automatically available to the program.
Practise this in the free Python course, where every exercise checks your code instantly.