Appending data to files in Python - Time & Space Complexity
When we add data to a file, it's important to know how the time it takes grows as the data grows.
We want to find out how the time to append changes when the file or data size changes.
Analyze the time complexity of the following code snippet.
with open('data.txt', 'a') as file:
for item in data_list:
file.write(item + '\n')
This code opens a file to add new lines at the end, writing each item from a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing each item to the file inside a loop.
- How many times: Once for every item in the list (n times).
As the number of items grows, the time to write grows in a similar way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 writes |
| 100 | 100 writes |
| 1000 | 1000 writes |
Pattern observation: The time grows directly with the number of items; doubling items doubles the work.
Time Complexity: O(n)
This means the time to append grows in a straight line with the number of items you add.
[X] Wrong: "Appending to a file is always instant, no matter how much data."
[OK] Correct: Each item still needs to be written, so more items take more time.
Understanding how file operations grow with data size helps you write efficient programs and explain your choices clearly.
"What if we buffered all items into one string and wrote once? How would the time complexity change?"