Reading Files Line-by-Line
Reading files line-by-line is a common operation in Python, and it's often used when working with large files or when you need to process the file's contents one line at a time. The most common way to read a file line-by-line is by using a for
loop with the readline()
method.
Here's an example:
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
In this example, the for
loop iterates over each line in the file, and the strip()
method is used to remove any leading or trailing whitespace characters.
Alternatively, you can use the readlines()
method to read all the lines at once and then iterate over them:
with open('example.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip())
This approach can be more efficient for smaller files, as it avoids the overhead of repeatedly calling readline()
.
You can also use the enumerate()
function to get the line number along with the line content:
with open('example.txt', 'r') as file:
for i, line in enumerate(file, start=1):
print(f"Line {i}: {line.strip()}")
This can be useful when you need to identify the specific line where an issue occurs.
Another common use case for reading files line-by-line is when you need to process the file's contents in a specific way, such as performing calculations or transforming the data. Here's an example that calculates the sum of all the numbers in a file:
total = 0
with open('numbers.txt', 'r') as file:
for line in file:
total += int(line.strip())
print(f"The sum of all the numbers is: {total}")
In this example, we're assuming that each line in the numbers.txt
file contains a single number. We then convert each line to an integer and add it to the total
variable.
By understanding how to read files line-by-line in Python, you can handle a wide range of file-related tasks, from processing log files to performing data analysis on large datasets.