1

From what I have seen, there are 2 ways to print to a file:

Method 1

file = open('myfile.txt', 'a')
file.write('sup')

# LATER ON

file.write('yo')

# AT THE END

file.close()

Method 2

with open('myfile.txt', 'a') as f:
   f.write('sup')

# LATER ON

with open('myfile.txt', 'a') as f:
   f.write('yo')

The problem with the first method, is that if the program were to end abruptly, the file does not close and is not saved. Because of this, I am currently using with and reopening the file everytime I want to print to it. However, I realize this may be a bad idea considering that I append to this file almost every 5 seconds. Is there a major performance hit in reopening the file with "with" before printing every time? And if so, how should I handle abrupt endings that result in the file not being closed using the first method.

MathMajor
  • 269
  • 1
  • 2
  • 13

2 Answers2

0

In the first method, what you want to do is to flush your changes to the file system after you are done with a set of writes. i.e.:

file.flush()

For something simple like what you had in your example, yes you should use with open... for interacting with files.

metatoaster
  • 17,419
  • 5
  • 55
  • 66
-3

I would recommend that you place your write operations inside a try: and your close in an finally:

with open('myfile.txt', 'a') as f:
    try:
        f.write('sup')
        # Extra Code
        f.write('yo')
    finally:
        f.close()

This ensures that f. will close properly if there is an error or if your a simply done running.

This is part of pythons cleanup functions

secumind
  • 1,141
  • 1
  • 17
  • 38
  • 1
    The context manager already calls close properly; the whole point of wrapping this in a contextmanager is to avoid writing extra file object handling code. Replace `# Extra Code` with `raise Exception` and sup will be written into myfile.txt with or without the try.. finally block. – metatoaster Mar 10 '14 at 02:53