gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:30:45 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com