python - 属性错误: 'module' object has no attribute 'TemporaryFile'

标签 python import

我是 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/

相关文章:

python - pycharm recnoizes 导入但仍然 ValueError : Attempted relative import beyond toplevel package django project on make migrations

java - 我可以使用 Hibernate 连接不同的数据库并从表中导入数据吗?没有预定义的对象类

python - 使用MRJob将作业提交到EMR群集

r - 如何将多个(excel)文件读入R?

python - 如何在同一个脚本中安装和导入python模块?

Python:避免此代码的 if 条件?

r - 如何导入.ods?

python - 给定一个对象的坐标,如何确定它位于旋转坐标系的哪个象限?

python - keras中model.compile的参数 'weighted_metrics'和model.fit_generator的参数 'class_weight'之间的区别?

c# - C# 和 Python 中的 int 是一回事吗?