无法从Python中读取tempfile

时间:2014-03-20 15:39:58

标签: python temporary-files

我试图在一个小python脚本中使用一些临时文件,并在使用tempfile-module时遇到问题:

测试码

import tempfile
with tempfile.NamedTemporaryFile() as temp:
    print temp.name
    temp.write('Some data')
    print temp.seek(0).read()

输出

  

s $ python tmpFileTester.py

     

/ var / folders / cp / 8kmr4fhs4l94y8fdc6g_84lw0000gn / T / tmpcDgrzF

     

回溯

     

(最近一次调用最后一次):文件“tmpFileTester.py”,第5行,in          print temp.seek(0).read()AttributeError:'NoneType'对象没有属性'read'

- >这种情况发生在使用MacOS 10.9和Python 2.7.5的MacBook上,也会出现“delete = False”。

有什么想法吗?这可能是一个菜鸟错误,但我找不到问题......

2 个答案:

答案 0 :(得分:3)

每当你在Python中链接方法并且得到它时,你可以打赌其中一个返回None(即使隐含地没有返回)。解决方案通常是将链条分成多行。

temp.seek(0)
print temp.read()

答案 1 :(得分:2)

file.seek返回None

您应该将以下声明分开:

print temp.seek(0).read()

分为两个陈述:

temp.seek(0)
print temp.read()