Today you will learn how to:
- Open a text file
- Read data from the file
- Use a loop to read every line
- Convert text into numbers
- Display results neatly
Create a file called:
numbers.txt
Put these values inside:
12
25
8
41
19Save it in the same folder as your Python program.
Start with this code:
file = open("numbers.txt", "r")
line = file.readline()
print(line)
file.close()✅ It opens the file ✅ Reads only the first line ✅ Prints it
Now use a loop:
file = open("numbers.txt", "r")
line = file.readline()
while line != "":
print(line)
line = file.readline()
file.close()The loop keeps running until Python reaches the end of the file.
When there are no more lines:
line == ""That means stop.
You may notice blank lines appear.
Use .strip():
file = open("numbers.txt", "r")
line = file.readline()
while line != "":
print(line.strip())
line = file.readline()
file.close().strip() removes:
- invisible spaces
- enter keys (
\n)
Everything in a file is read as text.
Convert each line:
file = open("numbers.txt", "r")
line = file.readline()
while line != "":
number = int(line)
print(number)
line = file.readline()
file.close()Now total everything:
file = open("numbers.txt", "r")
total = 0
line = file.readline()
while line != "":
number = int(line)
total += number
line = file.readline()
file.close()
print("Total =", total)Can you also find:
- largest number
- smallest number
- average
Python can read lines even easier:
file = open("numbers.txt", "r")
for line in file:
print(line.strip())
file.close()Answer:
- Why do we use
line = file.readline()before the loop? - What does
.strip()do? - Why do we convert to
int()?
Create your own file called:
highscores.txt
Add 5 game scores and calculate the total.