Writing file data in Python - Time & Space Complexity
When writing data to a file, it is important to understand how the time it takes grows as the amount of data increases.
We want to know how the program's work changes when we write more or less data.
Analyze the time complexity of the following code snippet.
with open('output.txt', 'w') as file:
for line in data:
file.write(line + '\n')
This code writes each line from a list called data into a file, adding a new line after each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing each line to the file inside a loop.
- How many times: Once for every line in the
datalist.
As the number of lines in data grows, the number of write operations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 writes |
| 100 | 100 writes |
| 1000 | 1000 writes |
Pattern observation: The work grows directly with the number of lines; double the lines, double the writes.
Time Complexity: O(n)
This means the time to write grows in a straight line with the number of lines you write.
[X] Wrong: "Writing to a file always takes the same time no matter how much data there is."
[OK] Correct: Writing more lines means more operations, so it takes longer as data grows.
Understanding how file writing time grows helps you explain performance in real programs that save data.
"What if we write all lines at once using one write call instead of a loop? How would the time complexity change?"