Python tempfile:坏了还是我做错了?

Ale*_*der 4 python temporary-files

对于一个小的python脚本,我想使用临时文件和tempfile模块.不知怎的,它没有给出预期的行为,我不知道我做错了什么或者这是一个错误:

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]'
Run Code Online (Sandbox Code Playgroud)

或者我只尝试了文本模式,但行为仍然很奇怪:

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.\n    i\x10 [ommitted]'
>>> tmp.seek(0)
>>> tmp.readline()
'test\x00\xa5\x8b\x02int or long, hash(a) is used instead.\n'
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏!


附加信息:来自Windows 7 Enterprise x64计算机上运行的当前Python XY发行版的Python 2.7.2(32位).在测试运行中,python在D:\ temp\myusername下的临时目录中创建了临时文件名"tmpvyocxj",其中运行了其他几个python进程.键入的命令,我没有尝试在脚本中重现它.行为没有改变,没有其他python进程在运行.


更新:此行为不仅限于tempfile模块,还适用于正常的file.read()和file.write()操作.根据CPython的说法,这两个函数只调用底层的libc fread()例程.在C标准中,写入之后没有搜索或刷新的读取的确切行为是未定义的,即每次实现都会导致不同的结果.

Nat*_*ate 8

我刚刚在Windows XP上的Python 2.7.1中重现了这种行为.

似乎是一个只有当你试图不首先寻求阅读时才会出现的错误.

那是:

>>> tmp.write('test')
>>> tmp.seek(0)
>>> tmp.read()
'test'
Run Code Online (Sandbox Code Playgroud)

>>> tmp.write('test')
>>> tmp.read()
'x\x01\x98\x00pfile.pyR\x05\x00\x00\x00G\x01\x00\x00s\x12 [blah blah blah]'
>>> tmp.seek(0)
>>> tmp.read()
'testx\x01\x98\x00pfile.pyR\x05\x00\x00\x00G\x01\x00\x00s\x12 [blah blah blah]'
Run Code Online (Sandbox Code Playgroud)

编辑:

对于踢球,我还检查:

  1. Windows 7,再次2.7.1(与我的XP安装相同的构建),并且在XP上看到了相同的行为.
  2. Cygwin版本2.6.5,并且此错误存在.