2

I am new to python.And i am learning the standard library.

Whenever i run the code below , it always raise the AttributeError... And it seems like there is something wrong with the import command.

Also , i try to run it on the interactive interpreator,and it works just fine.

The sample code

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

The error output

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'

My enviroment

  • ubuntu12.04
  • python2.7
4

2 回答 2

6

你给自己的文件命名了tempfile.py吗?如果是这样,请将其重命名,删除所有 *.pyc 文件,然后重试。

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

于 2012-12-27T16:54:48.577 回答
-2

尝试访问不属于模块中的类或函数的属性会引发 AttributeError 异常,该属性可能已在使用的更高版本的 Python 解释器中被弃用。我建议您检查您正在运行的 Python 的版本,并确保您的 dir(module) 包含您尝试使用的属性

于 2012-12-27T17:01:53.837 回答