from __future__ import print_function import os with open('@test', 'w') as fid: fid.write('a' *100) fid.close() fd = os.open('@test', os.O_RDONLY) try: fd2 = os.fdopen(fd, 'w') n = fd2.write('bbb') print('wrote %d to a read-only file' % n) # But it didn't really write ... except Exception as e: print('properly raised %r' % e) else: print('should raise, opening a ro descriptor for writing') try: os.close(fd) except: print('should not raise, fd remains open throughout') with open('@test') as fid: # even though fd2 claimed to write, the contents remain unchanged print(fid.read()) os.unlink('@test')