For a small python script, I would like to use a temporary file with the tempfile module. For some reason this does not give the expected behavior, and I do not know what I'm doing wrong, or if this is an error:
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import tempfile >>> tmp = tempfile.TemporaryFile() >>> tmp.read() '' >>> tmp.write('test') >>> tmp.read() 'P\xf6D\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ [ommitted]'
As an alternative, I tried only text mode, but the behavior is still weird:
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import tempfile >>> tmp = tempfile.TemporaryFile('w+t') >>> tmp.read() '' >>> tmp.write('test') >>> tmp.read() '\x00\xa5\x8b\x02int or long, hash(a) is used instead.\ni\x10 [ommitted]' >>> tmp.seek(0) >>> tmp.readline() 'test\x00\xa5\x8b\x02int or long, hash(a) is used instead.\n'
Any help is appreciated!
Additional Information: Python 2.7.2 (32 bit) from the current Python XY distribution, which runs on a computer running Windows 7 Enterprise x64. In a test run, python created a temporary file name "tmpvyocxj" in my temporary directory under the name D: \ temp \ myusername with several python processes running. The commands that I entered, I did not try to reproduce it in a script. The behavior does not change without any other python processes.
Update: This behavior is not limited to the tempfile module, as well as for the usual file.read () and file.write () operations. According to the CPython guys, both functions only call the libc fread () routines. In the C-standard, the exact reading behavior after writing without searching or blurring between them is undefined, that is, each implementation can lead to different results.