from __future__ import print_function import os NAME = 'output.txt' # Open same file for reading and writing. fw = open(NAME, 'wb') fr = open(NAME, 'rb') # Write and then read something from the file. fw.write(b'first') fw.flush() print('first:', fr.read()) # This next line triggers file handle getting stuck on Mac OS X / Python 2 # (works on Linux Python 2 and 3, Mac OS X Python 3 and pypy) fr.read() # Write and read some more from the file. fw.write(b'second') fw.flush() print('should be second:', fr.read()) # Reset file read handle to not be at EOF (needed for Mac OS X / Python 2) fr.seek(0, os.SEEK_CUR) print('should be empty:', fr.read()) fw.close() fr.close()