我是 python 新手。我正在学习标准库。
每当我运行下面的代码时,它总是会引发AttributeError...
而且导入命令好像有问题。
另外,我尝试在交互式解释器上运行它,它工作得很好。
示例代码
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
最佳答案
您是否为自己的文件命名了tempfile.py
?如果是这样,请重命名它,删除所有 *.pyc 文件,然后重试。
PS:提供带有回溯的错误的实际文本会告诉我们这些事情。
关于python - 属性错误: 'module' object has no attribute 'TemporaryFile' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14058133/