Search code examples
pythonfilefile-writing

When is best way to open a file to write to?


Let's say I need to crunch some data and then write the results to some file.

Would it be better to open the file first, then process the data, then write to the file?

with open('file', 'w') as f:
    summary = process_data()
    f.write(summary)

Or would it be better to open the file just before writing to it?

summary = process_data()
with open('file', 'w') as f:
    f.write(summary)

My intuition tells me that if process_data() requires a lot of memory and if file is large, there may be some issues with the first approach.

Edit:

To clarify from some of the responses, what are the pros and cons of each approach?


Solution

  • Python doesn’t have c-like scopes, only scoping constructs are def and class blocks, so summary is not cleaned up after with block has ended in the second example.

    I can think of only one difference: opening file in a write mode clears it, so if the process_data takes a long time inside the with block - it leaves file in an empty state for longer.

    If that’s not a concern this is 2+3 vs 3+2.