Last modified: Feb 14, 2026 By Alexander Williams
Python While Loop Read Numbers from Text File
Reading data from files is a core programming task. You often need to process numbers stored in text files. A while loop gives you fine-grained control over this process.
This guide shows you how to read numbers from a file using a while loop. We will cover the essential steps and best practices.
Why Use a While Loop for File Reading?
A for loop is common for iterating over lines. But a while loop is powerful when you don't know the file size in advance. It reads until a specific condition is met.
This condition is often the end of the file. You read line by line until there is nothing left. This method is robust and explicit.
Opening the File Correctly
The first step is to open the file. Use the built-in open() function. You must specify the file path and the mode.
For reading numbers, use the mode 'r' for reading. It is the default mode. Always use a context manager (with statement). It automatically closes the file.
# Open a file named 'data.txt' for reading
with open('data.txt', 'r') as file:
# File operations go here
pass
This approach prevents resource leaks. It is a fundamental practice in Python file handling. For more advanced control over text streams, see our guide on Python TextIOWrapper.
The Core While Loop Structure
Inside the with block, you set up the loop. The key is the .readline() method. It reads a single line from the file each time it is called.
The loop continues as long as the line is not empty. An empty string ('') signals the end of the file (EOF).
with open('data.txt', 'r') as file:
line = file.readline() # Read the first line
while line: # Continue while line is not empty
# Process the line here
print(line.strip())
line = file.readline() # Read the next line
The .strip() method removes whitespace like newline characters. This is crucial before converting text to numbers.
Converting Text to Numbers Safely
Text files store data as strings. You must convert these strings to integers or floats. Use int() or float() for conversion.
Wrap the conversion in a try-except block. This handles lines that are not valid numbers. It makes your code robust against dirty data.
numbers_list = []
with open('data.txt', 'r') as file:
line = file.readline()
while line:
stripped_line = line.strip()
if stripped_line: # Check if line is not empty after stripping
try:
# Try to convert to a float (or use int for integers)
number = float(stripped_line)
numbers_list.append(number)
except ValueError:
print(f"Skipping non-numeric line: '{stripped_line}'")
line = file.readline()
print("Numbers read:", numbers_list)
Complete Practical Example
Let's see a full example. Assume we have a file called numbers.txt with the following content.
42
18.5
-7
hello
99
world
3.14
We want to read all valid numbers and calculate their sum. We will skip non-numeric lines.
total = 0
count = 0
with open('numbers.txt', 'r') as file:
line = file.readline()
while line:
clean_line = line.strip()
if clean_line: # Proceed only if line is not empty
try:
num = float(clean_line)
total += num
count += 1
print(f"Added: {num}")
except ValueError:
print(f"Ignored: '{clean_line}' is not a number.")
line = file.readline()
print(f"\nSummary: Read {count} numbers.")
print(f"Their total sum is: {total}")
When you run this script, it will produce the following output.
Added: 42.0
Added: 18.5
Added: -7.0
Ignored: 'hello' is not a number.
Added: 99.0
Ignored: 'world' is not a number.
Added: 3.14
Summary: Read 5 numbers.
Their total sum is: 155.64
This example shows error handling and data processing in action. It's a common real-world pattern.
Key Advantages of the While Loop Method
Using a while loop with .readline() has benefits.
Explicit Control: You decide exactly when to read the next line. This is useful for complex file formats.
Memory Efficiency: It reads one line at a time. This is great for very large files that don't fit in memory.
Flexibility: You can easily add conditions to stop reading early. For instance, stop when you find a specific number or a sum threshold is reached.
When to Choose a For Loop Instead
A for loop is often simpler. You can iterate directly over the file object. It is the preferred method for straightforward line-by-line reading.
# Simpler alternative using a for loop
with open('data.txt') as file:
for line in file:
print(line.strip())
Choose the while loop when you need the extra control. Use the for loop for cleaner, more Pythonic code in standard scenarios.
If your numbers come from an image, you would first need to extract them. Our guide on Python Text Extraction from Images covers that initial step.
Conclusion
Reading numbers from a text file with a while loop is a fundamental skill. It combines file handling, loops, and data type conversion.
Remember to open files with a context manager. Use .readline() to control the reading flow. Always convert strings to numbers safely with error handling.
This method gives you power and flexibility. It is perfect for processing unknown or messy data files. Start with the examples here to build your own robust data readers.