AttributeError:'模块'对象没有属性' TemporaryFile'

时间:2012-12-27 16:48:52

标签: python import

我是python的新手。我正在学习标准库。

每当我运行下面的代码时,它总是会提升AttributeError... 而且导入命令似乎有问题。

此外,我尝试在交互式interpreator上运行它,它工作得很好。

示例代码

import tempfile
import os

#temp = tempfile.TemporaryFile()
temp = tempfile.mktemp()

print "tempfile","=>",temp

file = open(temp,"w+b")
file.write("*" * 1000)
file.seek(0)
print len(file.read()),"byte"
file.close()

try:
   os.remove(temp)
except OSError:
   pass

错误输出

Traceback (most recent call last):
  File "tempfile.py", line 1, in <module>
    import tempfile
  File "/home/zhkzyth/codeRep/pytest/tempfile.py", line 5, in <module>
    tempfile = tempfile.mktemp()
AttributeError: 'module' object has no attribute 'mktemp'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/apport_python_hook.py", line 66, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python2.7/dist-packages/apport/__init__.py", line 1, in <module>
    from apport.report import Report
  File "/usr/lib/python2.7/dist-packages/apport/report.py", line 12, in <module>
    import subprocess, tempfile, os.path, urllib, re, pwd, grp, os
  File "/home/zhkzyth/codeRep/pytest/tempfile.py", line 5, in <module>
    tempfile = tempfile.mktemp()
AttributeError: 'module' object has no attribute 'mktemp'

Original exception was:
Traceback (most recent call last):
  File "tempfile.py", line 1, in <module>
    import tempfile
  File "/home/zhkzyth/codeRep/pytest/tempfile.py", line 5, in <module>
    tempfile = tempfile.mktemp()
AttributeError: 'module' object has no attribute 'mktemp'

我的环境

  • ubuntu12.04
  • python2.7

2 个答案:

答案 0 :(得分:4)

您是否将自己的文件命名为tempfile.py?如果是这样,请重命名,删除所有* .pyc文件,然后重试。

PS:通过回溯提供错误的实际文本会告诉我们这些事情。

答案 1 :(得分:-2)

尝试访问不属于模块中的类或函数的属性会引发AttributeError异常,该属性可能已在稍后使用的Python解释器版本中弃用。我建议你查看你正在运行的Python的版本,并确保你的目录(模块)包含你试图使用的属性