AttributeError:“module”对象没有“temperaryfile”属性

2024-06-26 00:21:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

每当我运行下面的代码时,它总是提高AttributeError... 似乎import命令有问题。

另外,我试着在交互式的处理器上运行它,它运行得很好。

示例代码

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

Tags: inpyimportoslinetempfiletempfile
2条回答

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

注:提供错误的实际文本和回溯可以告诉我们这些事情。

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

相关问题 更多 >