Python Read File: Reading Text Files
To read a file in Python, open it with with open() and loop over its lines. Each line arrives as a string.
Each example first makes a small file, so it runs on its own. You don't need to learn that part here.
Read a file line by line
open() takes the filename, "r" for reading, and encoding="utf-8". A for loop then gives you one line at a time, in order.
with open("names.txt", "w", encoding="utf-8") as fixture: fixture.write("Ada\nSam\n")with open("names.txt", "r", encoding="utf-8") as source: for line in source: print(line.strip())This prints Ada, then Sam. Each line ends with a newline, "\n". strip() removes it, along with spaces at either end. with closes the file when the indented block ends.
Split a line into numbers
A line is always text. split() breaks it into words at the spaces. Convert each word with int() before doing maths.
with open("cards.txt", "w", encoding="utf-8") as fixture: fixture.write("7 10\n3 4\n")with open("cards.txt", "r", encoding="utf-8") as source: for line in source: parts = line.split() print(int(parts[0]) + int(parts[1]))This prints 17, then 7. For the first line, parts is the list ["7", "10"].
See also: String methods, For loops.
Your turn
Open path for reading, loop over its lines, and print each line with strip().
Mia Leo
path = "lesson-read-task.txt"with open(path, "w", encoding="utf-8") as fixture: fixture.write("Mia\nLeo\n")# add three lines: open path with with, loop over the lines, print each stripped lineAdvanced reading
- Writing text files — create a file and add lines to the end of it.
- Reading a whole file — get all the text at once, and handle empty or missing files.
- JSON — save and load lists and dictionaries in a file.