File system interaction basics in Python - Time & Space Complexity
When working with files, it's important to know how the time to read or write changes as files get bigger.
We want to see how the program's work grows when the file size grows.
Analyze the time complexity of the following code snippet.
with open('example.txt', 'r') as file:
content = file.read()
for line in content.splitlines():
print(line)
This code reads a whole file, splits it into lines, and prints each line.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each line in the file content.
- How many times: Once for every line in the file, which depends on file size.
As the file gets bigger, the number of lines grows, so the loop runs more times.
| Input Size (n lines) | Approx. Operations |
|---|---|
| 10 | About 10 print operations |
| 100 | About 100 print operations |
| 1000 | 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 run 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 its size."
[OK] Correct: Bigger files have more data, so reading and processing them takes more time.
Understanding how file size affects program speed helps you write better code and answer questions clearly in interviews.
"What if we read the file line by line instead of all at once? How would the time complexity change?"