Reading file data in Python - Time & Space Complexity
When reading data from a file, it is important to understand how the time taken grows as the file size increases.
We want to know how the program's running time changes when the file has more lines or characters.
Analyze the time complexity of the following code snippet.
with open('data.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip())
This code reads all lines from 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 number of lines in the file grows, the time to read and print each line grows in a similar way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 lines read and printed |
| 100 | About 100 lines read and printed |
| 1000 | About 1000 lines read and printed |
Pattern observation: The time grows roughly in direct proportion to the number of lines.
Time Complexity: O(n)
This means the time taken grows linearly 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 more lines or characters in the file, the longer it takes to read and process each one.
Understanding how file reading time grows helps you write efficient programs and explain your reasoning clearly in interviews.
"What if we read the file line by line inside the loop instead of reading all lines at once? How would the time complexity change?"