Why file handling is required in Python - Performance Analysis
When working with files in Python, it is important to understand how the time to read or write data grows as the file size increases.
We want to know how the program's running time changes when handling bigger files.
Analyze the time complexity of reading a file line by line.
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
This code opens a file and prints each line after removing extra spaces.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each line in the file.
- How many times: Once for every line in the file.
As the file gets bigger, the number of lines grows, so the program does more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 lines | About 10 print operations |
| 100 lines | About 100 print operations |
| 1000 lines | About 1000 print operations |
Pattern observation: The work grows directly with the number of lines in the file.
Time Complexity: O(n)
This means the time to read and print grows in a straight line with the number of lines in the file.
[X] Wrong: "Reading a file always takes the same time no matter how big it is."
[OK] Correct: The bigger the file, the more lines or data there are to process, so it takes longer.
Understanding how file size affects program speed helps you write better code and explain your thinking clearly in interviews.
"What if we read the whole file at once instead of line by line? How would the time complexity change?"