Need to wrangle data from a file in Python? Reading it line by line is a fundamental skill. Forget loading the entire file into memory – this approach is memory-efficient, especially for large files.
So, how do we do it?
The simplest way is using a `for` loop with the file object:
```python
with open('my_file.txt', 'r') as file:
for line in file:
print(line.strip()) # Process each line (remove leading/trailing whitespace)
```
Here's what's happening:
1. `with open(...)` ensures the file is properly closed, even if errors occur.
2. `'r'` opens the file in read mode.
3. The `for` loop iterates through each line in the file.
4. `line.strip()` removes any leading or trailing whitespace (like newline characters).
This method reads each line sequentially, allowing you to process or analyze the data as it comes in. Master this technique, and you'll be reading and processing files like a Python pro!